TSQL Where子句在字符串查询中

时间:2014-02-21 14:07:45

标签: sql tsql

我的查询:

SET @s_query =

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

我正在使用参数运行存储过程:

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

得到错误:

" Invalid column name 'Adam'.

3 个答案:

答案 0 :(得分:3)

看起来你只是没有引用你的字符串。你的代码出现的方式,看起来像SQL:

Where FirstName = Adam

但是你希望它看起来像:

Where FirstName = 'Adam'

因此,您需要更改代码行,以便为其提供所需的单引号。请参阅下面的修改后的代码集:

SET @s_query =

'Select ROW_NUMBER() OVER (ORDER BY ' + @ColNames + ') AS ##RowNum, 
'+@ColNames+' INTO ##Results' +
' From TableA
Where FirstName = ''' +@Search+ ''' 
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

答案 1 :(得分:2)

问题似乎在于您指定FirstName的条件,您有:

Where FirstName = ' +@Search+ '

将从字面上翻译成:

Where FirstName = Adam

请注意搜索条件Adam周围缺少引号。

请尝试此操作,以确保包含其他引号:

Where FirstName = ''' +@Search+ '''

最终会给出:

Where FirstName = 'Adam'

答案 2 :(得分:0)

其他人已经指出字符串标准周围缺少引号(= Adam,而不是='Adam')。

我使用不同的技术来构建要调用的SQL,方法是构建模板并替换“parameters”:

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
       )

我发现这样可以更容易地看到您尝试创建的代码的结构,包括应该有引号的地方。