0
我創建了一個工作動態數據透視表。在Dynamic Pivot中包含WHERE子句
DECLARE
@AttributeNames as NVARCHAR(MAX),
@SQL as NVARCHAR(MAX);
DECLARE
@AssetGroup as NVARCHAR(MAX) = 'Water',
@AssetType as NVARCHAR(MAX)= 'Water Meters',
@RecStatus as NVARCHAR(MAX) = 'I';
SET @AttributeNames = STUFF(
(SELECT N',' + QUOTENAME(AttributeName) AS [text()]
FROM (SELECT DISTINCT G1_ATTRIBUTE_NAME as AttributeName
FROM dbo.GASSET_MASTER INNER JOIN
dbo.GASSET_ATTRIBUTE ON dbo.GASSET_MASTER.SERV_PROV_CODE = dbo.GASSET_ATTRIBUTE.SERV_PROV_CODE AND
dbo.GASSET_MASTER.G1_ASSET_SEQ_NBR = dbo.GASSET_ATTRIBUTE.G1_ASSET_SEQ_NBR
--WHERE (dbo.GASSET_MASTER.G1_ASSET_GROUP = ''' + @AssetGroup + ''') AND (dbo.GASSET_MASTER.G1_ASSET_TYPE = ''' + @AssetType + ''')
) AS AttributeName
ORDER BY AttributeName
FOR XML PATH('')),
1,1, N'');
SET @SQL = N'SELECT *
FROM (SELECT dbo.GASSET_MASTER.G1_ASSET_ID, dbo.GASSET_ATTRIBUTE.G1_ASSET_SEQ_NBR, dbo.GASSET_ATTRIBUTE.G1_ATTRIBUTE_NAME,
dbo.GASSET_ATTRIBUTE.G1_ATTRIBUTE_VALUE, dbo.GASSET_MASTER.G1_ASSET_GROUP, dbo.GASSET_MASTER.G1_ASSET_TYPE,
dbo.GASSET_MASTER.G1_ASSET_STATUS, dbo.GASSET_MASTER.REC_STATUS
FROM dbo.GASSET_MASTER LEFT OUTER JOIN
dbo.GASSET_ATTRIBUTE ON dbo.GASSET_MASTER.SERV_PROV_CODE = dbo.GASSET_ATTRIBUTE.SERV_PROV_CODE AND
dbo.GASSET_MASTER.G1_ASSET_SEQ_NBR = dbo.GASSET_ATTRIBUTE.G1_ASSET_SEQ_NBR
WHERE (dbo.GASSET_MASTER.G1_ASSET_GROUP = ''' + @AssetGroup + ''') AND (dbo.GASSET_MASTER.G1_ASSET_TYPE = ''' + @AssetType + ''') AND (dbo.GASSET_MASTER.REC_STATUS <> ''' + @RecStatus + ''')) as SState
PIVOT (
MAX(G1_ATTRIBUTE_VALUE)
FOR G1_ATTRIBUTE_NAME IN(' + @AttributeNames + N')) AS P;';
Print @SQL
此代碼導致我認爲是一個正確格式化的樞軸。但是,當我在構建列時嘗試使用註釋掉的WHERE
子句時,不會返回任何記錄,也不會收到錯誤。
--WHERE (dbo.GASSET_MASTER.G1_ASSET_GROUP = ''' + @AssetGroup + ''') AND (dbo.GASSET_MASTER.G1_ASSET_TYPE = ''' + @AssetType + ''')
我試圖以許多不同的方式更改WHERE
子句,但沒有成功。任何想法如何我可以做到這一點不同?
因此,它是工作或它不工作?或者,你只是在尋找一種更好的方式來完成相同的目標? – Jesse 2013-05-02 00:24:44