我得到了非常簡單的查詢,但我無法使其工作。 請幫忙。謝謝動態樞軸Sql服務器
我跟着嘖嘖,但我的查詢不起作用
DECLARE @ColumnName NVARCHAR(MAX) = ''
DECLARE @Query NVARCHAR(MAX) = ''
DECLARE @Site NVARCHAR(MAX) = ''
DECLARE @Date NVARCHAR(MAX) = ''
DECLARE @MOnth NVARCHAR(MAX) = ''
SELECT @ColumnName += QUOTENAME([Product Category]) + ','
FROM
(
SELECT DISTINCT [Product Category]
FROM vw_TTMTALK_BREAKDOWN_DETAIL_LINE
WHERE [Customer No] = 'SLPIP' AND
DATEPART(yyyy, [Posting Date])= '2016' AND
CONVERT(CHAR(3), [Posting Date], 0)= 'Jan'
GROUP BY [Customer No], [Product Category]
) AS T1
SET @ColumnName = LEFT(@ColumnName,LEN(@ColumnName)-1)
set @Site = 'SLPIP'
set @Date = '2016'
set @Month = 'Jan'
SET @Query = 'SELECT * FROM
(
SELECT [Customer No], [Product Category]
FROM vw_TTMTALK_BREAKDOWN_DETAIL_LINE
WHERE [Customer No] = ' + @Site + ' AND
DATEPART(yyyy, [Posting Date])=' + @Date + ' AND
CONVERT(CHAR(3), [Posting Date], 0)=' + @Month + '
--GROUP BY [Customer No], [Product Category]
) T2
PIVOT (
COUNT([Customer No])
FOR [Product Category] IN (' + @ColumnName + ')
) T3'
--print @Query
EXEC sp_executesql @Query
錯誤
Msg 207, Level 16, State 1, Line 5
Invalid column name 'SLPIP'.
Msg 207, Level 16, State 1, Line 7
Invalid column name 'Jan'.
動態查詢中缺少@site周圍的標記。和大約一個月。假定兩者都是字符串數據類型。在網站前後添加char(39)。例如:'WHERE [Customer No] ='+ char(39)+ @ Site + char(39)'AND' – xQbert
謝謝您的主席xQbert您的解決方案的工作 –