简体   繁体   中英

Table doesn't exist error when execuitng dynamic sql with sp_executesql

If I open a connection to a database, for example, with SSMS, and I run a query like this:

SELECT * FROM MySchema.MyTable

the query is executed without error.

If I run it as dynamic sql like this

declare var @qry nvarchar(200);
set @qry = N'SELECT * FROM MySchema.MyTable'
exec master.sys.sp_executesql @qry

I get an error stating that the table doesn't exist.

If I put the database name prefix before MySchema.MyTable name, ie MyDb.MySchema.MyTable the query runs correctly.

How can I avoid the error without specifying the database name in the dyanmic SQL?

try this!

change this

exec master.sys.sp_executesql @qry

to

exec sp_executesql @qry

or

exec @qry

Both answers by Recursive and koushik veldanda work fine, but this gives a deeper insight to the problem:

The problem is that executing a query with

exec master.sys.sp_execute_sql @qry

changes the context to the master database, so MySchema.MyTable is not accesible, because it doesn't belong to master , but to MyDb .

If the query is executed with

exec sys.sp_execute_sql @qry

the context is maintained in the current database, so the table is accesible, and the query runs without problem.

Use

 exec @sql 

is enough if there are any output parameters then go with

 exec sp_executesql 

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