2014-02-21 139 views
0

我的查詢:TSQL Where子句中查詢字符串

SET @s_query = 

'Select ROW_NUMBER() OVER (ORDER BY ' + @ColNames + ') AS ##RowNum, 
'[email protected]+' INTO ##Results' + 
' From TableA 
Where FirstName = ' [email protected]+ ' 
ORDER BY FirstName'; 

我運行的是存儲過程的參數:

@Search = 'Adam', @ColName = 'FirstName','LastName' 

而得到的錯誤:

" Invalid column name 'Adam'. 
+0

你的意思是@ColName ='''FirstName','LastName''''?如果這不是概率,請粘貼@s_query的完整sql和轉儲。 –

+0

亞歷克斯這些只是參數問題是在哪裏,我得到一個錯誤,當運行SP的where子句。它假定'亞當'是一列 – user2906420

回答

3

看起來你只是沒有引用你的字符串。你的代碼出來的方式,到SQL它看起來像:

Where FirstName = Adam 

但你希望它看起來像:

Where FirstName = 'Adam' 

所以,你會想改變該行代碼的給它它需要的單引號。請參見下面的修改代碼集:

SET @s_query = 

'Select ROW_NUMBER() OVER (ORDER BY ' + @ColNames + ') AS ##RowNum, 
'[email protected]+' INTO ##Results' + 
' From TableA 
Where FirstName = ''' [email protected]+ ''' 
ORDER BY FirstName'; 

現在您的查詢將改爲:

Select ROW_NUMBER() OVER (ORDER BY FirstName, LastName) AS ##RowNum,  
FirstName, LastName INTO ##Results From TableA  
Where FirstName = 'Adam'  
ORDER BY FirstName, LastName 
2

出現的問題是,你指定的條件爲FirstName,您有:

Where FirstName = ' [email protected]+ ' 

哪將直接翻譯爲:

Where FirstName = Adam 

請注意搜索標準Adam附近缺少的報價。

試試這個,以保證更多的報價包括:

Where FirstName = ''' [email protected]+ ''' 

這會終於放棄:

Where FirstName = 'Adam' 
0

其他人已經指出了字符串標準周圍缺少引號(=亞當,而不是='亞當')。

我使用不同的技術來構建SQL調用,通過構建模板和更換「參數」:

declare @s_QueryTemplate = 
' 
Select ROW_NUMBER() OVER (ORDER BY <<ORDER BY COLUMN NAMES>>) AS ##RowNum, <<COLUMN NAMES>> 
INTO ##Results 
From TableA 
Where FirstName = ''<<SEARCH VALUE>>'' 
ORDER BY FirstName 
' 

SET @s_query = 
REPLACE(
REPLACE(
REPLACE(
      @s_QueryTemplate 
     , '<<ORDER BY COLUMN NAMES>>', @ColNames 
     ), '<<COLUMN NAMES>>', @ColNames 
     ), '<<SEARCH VALUE>>', @Search 
     ) 

我覺得這使得它更容易看到你的代碼的結構試圖創造,包括應該有引號的地方。