我尝试运行下面的代码来将由逗号分隔的ProvisionedDirectAddress列值的值拆分为一个新列。但是,它似乎不起作用
DECLARE @SQLQuery AS NVARCHAR(MAX)
DECLARE @PivotColumns AS NVARCHAR(MAX)
SELECT @PivotColumns= COALESCE(@PivotColumns + ',','') + QUOTENAME(ProvisionedDirectAddress)
FROM (SELECT distinct ProvisionedDirectAddress from SearchTable) AS PivotExample
SET @SQLQuery=N'
SELECT A.Name,T.* FROM
(
select NPI,MAX(firstname)FirstName from SearchTable
GROUP BY NPI
) a
inner join
(
select NPI, '+@PivotColumns+' from
(
SELECT
NPI,MAX(firstname)FirstName,MAX(LastName)LastName,
STUFF(
(SELECT "," + ProvisionedDirectAddress
FROM SearchTable
FOR XML PATH (''))
, 1, 1, '') AS ProvisionedDirectAddress
FROM SearchTable GROUP BY NPI
) B
Pivot(
Min (ProvisionedDirectAddress) for ProvisionedDirectAddress in('+@PivotColumns+')
)
as Pivottable
) t on t.NPI=A.NPI'
EXEC sp_executesql @SQLQuery
我需要用逗号分隔的Provisioneddirectaddress列值 出现为新列