In TableB i have few more records with more categoryid and categoryname.
It seems that you need a Dynamic Pivot query.
Check this:
DECLARE @sql_str VARCHAR(MAX)
DECLARE @spread_elements VARCHAR(MAX)
SELECT @spread_elements = ISNULL(@spread_elements + ',','') + QUOTENAME(Categoryname)
FROM TableA A JOIN TableB B ON A.SrNo=B.SrN
GROUP BY Categoryname
--PRINT @spread_elements
SET @sql_str ='
;WITH CTE AS
(
SELECT A.*,B.Categoryid,B.Categoryname
FROM TableA A JOIN TableB B ON A.SrNo=B.SrN
)
SELECT *
FROM CTE
PIVOT(MAX(Categoryid) FOR Categoryname IN('+ @spread_elements +'))P'
--PRINT (@sql_str)
EXEC (@sql_str)
Best regards,
LiHong
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.