SQL Server +动态查询'列名无效'

时间:2013-02-26 20:07:33

标签: sql

我正在尝试执行以下动态查询但是我收到一个错误:无效的列名称'cat'

 DECLARE @SQLDelQuery AS NVARCHAR(1200)   
 DECLARE @MemberNames varchar(50)

 SET @MemberNames = 'cat'

      SET @SQLDelQuery = 'SELECT [Email] FROM [aspnet_Membership] am
      INNER JOIN [aspnet_Users] u
      ON (am.UserId = u.UserId)
      INNER JOIN [Member] m
      ON (am.UserId = m.UserId)
      WHERE u.UserName IN (' + @MemberNames + ')

  EXECUTE(@SQLDelQuery)

如果我将其更改为正常查询,我很好:

SELECT [Email] FROM [aspnet_Membership] am
  INNER JOIN [aspnet_Users] u
  ON (am.UserId = u.UserId)
  INNER JOIN [Member] m
  ON (am.UserId = m.UserId)
  WHERE u.UserName IN ('cat')

任何人都可以指出我的错误?感谢。

4 个答案:

答案 0 :(得分:6)

由于cat是一个varchar,你需要在它周围加上单引号,你需要在sql字符串中放置IN子句的右括号。

新代码将是:

DECLARE @SQLDelQuery AS NVARCHAR(1200)   
 DECLARE @MemberNames varchar(50)

 SET @MemberNames = 'cat'

      SET @SQLDelQuery = 'SELECT [Email] FROM [aspnet_Membership] am
      INNER JOIN [aspnet_Users] u
      ON (am.UserId = u.UserId)
      INNER JOIN [Member] m
      ON (am.UserId = m.UserId)
      WHERE u.UserName IN (''' + @MemberNames + ''')'

  EXECUTE(@SQLDelQuery)

查看打印了查询字符串的SQL Fiddle Demo。这将生成如下查询字符串:

SELECT [Email] 
FROM [aspnet_Membership] am 
INNER JOIN [aspnet_Users] u 
  ON (am.UserId = u.UserId) 
INNER JOIN [Member] m 
  ON (am.UserId = m.UserId) 
WHERE u.UserName IN ('cat') -- cat surrounded in single quotes

答案 1 :(得分:2)

您需要将其作为字符串传递给动态查询

 SET @MemberNames = '''cat'''

resulted query 的差异是

WHERE u.UserName IN (cat) -- cat is taking as a column name here
WHERE u.UserName IN ('cat') -- cat is taking as a string here

答案 2 :(得分:1)

你的字符串:

WHERE u.UserName IN (' + @MemberNames + ')

将评估为:

WHERE u.UserName IN (cat)

因为你所拥有的撇号只是封装了字符串,并且字符串文字周围没有额外的撇号。

你需要:

WHERE u.UserName IN (''' + @MemberNames + ''')

或者,您可以按原样保留查询,并在@MemberNames变量中使用撇号分隔每个ID:

SET @MemberName = '''cat'''           -- for a single user
SET @MemberName = '''cat'', ''dog'''  -- for multiple users

答案 3 :(得分:0)

您的动态查询使用'个字符作为字符串分隔符,因此在构建字符串后,最后一行最终会像这样读取:

WHERE u.UserName IN (cat)

根据这一点,cat读起来就像一个列名。

要解决此问题,您需要在

的定义中包含转义的'字符
`SET @MemberNames = '''cat'''` 

或用于构建sql的字符串:

`WHERE u.UserName IN (''' + @MemberNames + ''')'`