Dynamic SQL unknown column name

Discussion in 'Databases' started by jimspicer, Aug 21, 2011.

Thread Status:
Threads that have been inactive for 5 years or longer are closed to further replies. Please start a new thread.
  1. Hi,
    We are using common table structures with different names so Dynamic SQL may work for us. But I am having a problem with this query:

    DECLARE @SQL nvarchar(4000)

    SET @SQL = 'SELECT UsersData_ID FROM ' + @Tablename + ' WHERE Users = ' + @UserName

    exec sp_executeSql @SQL

    The @UserName column contains email addresses. When I run this query I get this error...

    The multi-part identifier "[email protected]" could not be bound.

    or I get this error...

    Invalid column name 'jim@spicer'

    It seems the query engine doesn't like the @ sign but what can I do about it? All of our other dynamic SQL queries are working. Thanks for any help, Jim Spicer
     
  2. reduced scope

    Hi wisemx,
    Thanks for the reply. I tried reducing the Scope of the query by adding parameters and the ORDER BY but still getting the same errors. Have tried changing the name of the field, but the error stays the same. This is a show-stopper for us. The same query in static SQL works fine.
     
  3. sql server version

    Hi again,
    We're on SQL Server 2005...did this get fixed in 2008?

    TIA,
    Jim
     
  4. Possibly, I'm not sure but there are tons of fixes in it.
    You also get more here with 2008 and R2 so it is worth upgrading.
     
  5. Solution!

    Hi,
    I asked Tech Support to look at my code also, and they suggested I try this:

    SET @SQL = 'SELECT UsersData_ID FROM ' + @Tablename + ' WHERE Users = ' + quotename(@Users,'''') + ' AND blah blah

    The quotes are four single quotes. I had read this in the literature but didn't know to apply it in this situation. Thanks for the help Jorge and Wise.
     
  6. So you got it to work? If so, good job ;-)
     
Thread Status:
Threads that have been inactive for 5 years or longer are closed to further replies. Please start a new thread.

Share This Page