A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
Please check:
DECLARE @sql nvarchar(max)
DECLARE @s nvarchar(max)
SELECT @s=STUFF(( SELECT DISTINCT ',['+CAST(Section as nvarchar)+']'
FROM #table1 FOR XML PATH('') ), 1, 1, '')
SET @sql=N';WITH cte
as(SELECT EmpName,CAST(Section as nvarchar) Section
FROM #table1)
SELECT * FROM (SELECT EmpName,Section FROM cte) as t
pivot (MAX(Section) FOR Section in ('+@s+')) as p'
EXECUTE sp_executesql @sql
Output:
If you have any question, please feel free to let me know.
Regards
Echo
If the answer is helpful, please click "Accept Answer" and upvote it.