Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server + Dynamic Query 'Invalid Column Name'

Tags:

sql

I am trying to execute the following dynamic query but I got an error: 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)

If I change it to the normal query I am fine:

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')

Anyone can point out my error? Thanks.

like image 365
k80sg Avatar asked Feb 26 '13 20:02

k80sg


3 Answers

Since cat is a varchar you need to include single quotes around it and you need to place the closing parentheses for the IN clause inside of the sql string.

The new code will be:

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)

See a SQL Fiddle Demo with the query string printed. This generates a query string like this:

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
like image 187
Taryn Avatar answered Oct 31 '22 22:10

Taryn


You need to pass it as a string to the dynamic query

 SET @MemberNames = '''cat'''

Difference in the resulted query is

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
like image 44
Kaf Avatar answered Oct 31 '22 21:10

Kaf


Your string:

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

will evaluate to:

WHERE u.UserName IN (cat)

because the apostrophes you have are just encapsulating the string, and there are no extra apostrophes around the string literal.

You need:

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

Alternately, you can leave your query as is, and seperate each ID with apostrophes in your @MemberNames variable:

SET @MemberName = '''cat'''           -- for a single user
SET @MemberName = '''cat'', ''dog'''  -- for multiple users
like image 2
LittleBobbyTables - Au Revoir Avatar answered Oct 31 '22 22:10

LittleBobbyTables - Au Revoir