1

I have created a working dynamic pivot.

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

This code results in what i believe to be a properly formatted pivot. But when I attempt to use the commented out WHERE clause when building the columns no records are returned and no errors are received.

--WHERE     (dbo.GASSET_MASTER.G1_ASSET_GROUP = ''' + @AssetGroup + ''') AND (dbo.GASSET_MASTER.G1_ASSET_TYPE = ''' + @AssetType + ''')

I have attempted to change the WHERE clause in a number of different ways with no success. Any ideas how I could do this differently?

4

1 回答 1

4

将注释行更改为这一行:

WHERE     (dbo.GASSET_MASTER.G1_ASSET_GROUP = @AssetGroup ) AND (dbo.GASSET_MASTER.G1_ASSET_TYPE = @AssetType )

说明:第一个查询不是动态查询,不需要嵌入'

于 2013-05-02T00:12:37.690 回答