简体   繁体   中英

Dynamic SQL - Invalid object name error

I am using dynamic SQL on SQL Server 2008 to select specified columns from a row but I keep getting the following error:

Invalid object name 'Form'

My code is as follows:

DECLARE @SQL varchar(MAX)

SET @SQL = 'select 
[City],[Place]'
+
'
from Form where [Age:] =  20'

EXEC (@SQL)

I also tried using + QUOTENAME(@Table) and declared @Table as nvarchar(MAX) but could not define that @Table is basically the Form table in my database.

As I checked the previous examples , people were able to select columns from tables the same way without getting errors, so what could be the reason for the error I get? Should I use @QUOTENAME function at all?

Help will be appreciated.

Try below query and if you still get error check basic things first.

DECLARE @SQL varchar(MAX)
SET @SQL = 'select [City],[Place] from [Form] where [Age] =  20'
EXEC (@SQL)
  1. Is table [Form] present in database ?
  2. Are you running in correct DB?
  3. I see ":" after AGE is that in col name ?
  4. If Age is varchar try to add "'" before and after 20.

You describe @table . Table is a reserved keyword, so it's a good practice not to use that word. Lets assume @mytable is a variable containing the table name for the query. In that case, you concatenate like you do with the rest of the string. You also need to be connected to the database you are trying to query from.

For example:

DECLARE @SQL varchar(MAX)
DECLARE @mytable varchar(1000) = 'Form' --put the table name here

SET @SQL = 'select [City], [Place] '
         + 'from ' + @mytable + ' where [Age:] =  20'

EXEC (@SQL)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM