2016-07-10 163 views
0

我有一個動態的支點寫成下面,我需要添加一個where條款動態支點where子句

DECLARE @cols AS NVARCHAR(MAX), 
@query AS NVARCHAR(MAX),@uniqId varchar(50); 

set @uniqId = 'IN0s3Z0n8z4v' 

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.DisplayLabel) 
     FROM [dbo].[CountyCaseUserData] c where UniqueEntryId = @uniqId 
     FOR XML PATH(''), TYPE 
     ).value('.', 'NVARCHAR(MAX)') 
    ,1,1,'') 

print @cols 
set @query = 'SELECT ' + @cols + ' 
from 
     (
      SELECT UserInput, DisplayLabel,row_number() 
         over (partition by DisplayLabel order by CCId) AS No 
      from [dbo].[CountyCaseUserData] where UniqueEntryId = @uniqId 
     ) x 
     pivot 
     (
      max(UserInput) 
      for DisplayLabel in (' + @cols + ') 
     ) p '; 


execute(@query) 

但在執行的時候,我得到一個消息

必須聲明標量變量「 @uniqId「

我在這裏錯過了什麼?

+2

首先聲明'@ uniqid'然後是'這裏UniqueEntryId = '' '+ @uniqId + ''') x'或使用'sp_executesql'作爲參數傳遞。 –

+0

執行不知道變量。所以你需要將它添加到Les H建議的@query中。 – LukStorms

回答

1

爲別人指出的那樣,

變化execute(@query)

exec sp_executesql @query, N'@uniqId varchar(50)', @uniqId