5

我正在尝试执行以下动态查询,但出现错误:Invalid column name '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

4 回答 4

8

由于cat是 varchar,因此您需要在其周围包含单引号,并且您需要将IN子句的右括号放在 sql 字符串内。

新代码将是:

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 演示。这会生成一个查询字符串,如下所示:

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
于 2013-02-26T20:09:51.200 回答
2

你的字符串:

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
于 2013-02-26T20:09:42.807 回答
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
于 2013-02-26T20:10:13.613 回答
0

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

WHERE u.UserName IN (cat)

据此,cat读起来像一个列名。

要修复它,您需要'在定义中包含转义字符

`SET @MemberNames = '''cat'''` 

或在用于构建 sql 的字符串中:

`WHERE u.UserName IN (''' + @MemberNames + ''')'`
于 2013-02-26T20:10:20.230 回答