0

我有一个字符串变量,其中包含一个动态列标题列表,如下所示:

DECLARE @Pivot VARCHAR(4000) 
SELECT @Pivot = STUFF((SELECT DISTINCT ']),MAX([' + valv.ITEM_CMDT_N + ']) AS ' + valv.ITEM_CMDT_N + ',MAX([' + valv.ITEM_CMDT_N + ' - Date' FROM [dbo].[VEND_ASGN_LKUP_VAL] valv INNER JOIN [dbo].[VEND_ASGN] va ON valv.CTRY_C = va.CTRY_C AND valv.CY_DATE_D = va.CY_DATE_D WHERE va.VEND_ASGN_I = 10 AND va.ACTV_F= 1 AND valv.ACTV_F = 1 ORDER BY ']),MAX([' + valv.ITEM_CMDT_N + ']) AS ' + valv.ITEM_CMDT_N + ',MAX([' + valv.ITEM_CMDT_N + ' - Date' FOR XML PATH('')),1,3,'') + '])'

这可以很好地工作,并产生如下字符串:

MAX([TEST]) AS TEST,MAX([TEST - Date]),MAX([TEST2]) AS TEST2,MAX([TEST2 - Date])

但是请注意,只有第一个字段 ( ITEM_CMDT_N) 包含别名。如果我尝试将类似的代码添加到第二个字段的别名,它看起来像这样:

SELECT @Pivot = STUFF((SELECT DISTINCT ']) AS [' + valv.ITEM_CMDT_N + ' - Date],MAX([' + valv.ITEM_CMDT_N + ']) AS ' + valv.ITEM_CMDT_N + ',MAX([' + valv.ITEM_CMDT_N + ' - Date' FROM [dbo].[VEND_ASGN_LKUP_VAL] valv INNER JOIN [dbo].[VEND_ASGN] va ON valv.CTRY_C = va.CTRY_C AND valv.CY_DATE_D = va.CY_DATE_D WHERE va.VEND_ASGN_I = 10 AND va.ACTV_F= 1 AND valv.ACTV_F = 1 ORDER BY ']) AS [' + valv.ITEM_CMDT_N + ' - Date],MAX([' + valv.ITEM_CMDT_N + ']) AS ' + valv.ITEM_CMDT_N + ',MAX([' + valv.ITEM_CMDT_N + ' - Date' FOR XML PATH('')),1,3,'') + '])'

并产生这样的字符串:

AS [TEST - Date],MAX([TEST]) AS TEST,MAX([TEST - Date]) AS [TEST2 - Date],MAX([TEST2]) AS TEST2,MAX([TEST2 - Date])

这显然不是我的目标。如何'valv.ITEM_CMDT_N + ' - Date'在仍然使用 FOR XML PATH 代码的同时调整此字符串初始化以包含字段的别名?谢谢!

4

1 回答 1

0
SELECT @Pivot = STUFF((SELECT DISTINCT ',MAX([' + valv.ITEM_CMDT_N + ']) AS [' + valv.ITEM_CMDT_N + '],MAX([' + valv.ITEM_CMDT_N + ' - Date]) AS [' + valv.ITEM_CMDT_N + ' - Date]' FROM [dbo].[VEND_ASGN_LKUP_VAL] valv INNER JOIN [dbo].[VEND_ASGN] va ON valv.CTRY_C = va.CTRY_C AND valv.CY_DATE_D = va.CY_DATE_D WHERE va.VEND_ASGN_I = 10 AND va.ACTV_F= 1 AND valv.ACTV_F = 1 ORDER BY ',MAX([' + valv.ITEM_CMDT_N + ']) AS [' + valv.ITEM_CMDT_N + '],MAX([' + valv.ITEM_CMDT_N + ' - Date]) AS [' + valv.ITEM_CMDT_N + ' - Date]' FOR XML PATH('')),1,1,'') 
于 2013-10-01T17:02:11.137 回答