简体   繁体   中英

A Stored Procedure for multiple tables

I want to write a stored procedure for my Tables that have a similar format

for example

tbl#Students(id int,name nvarchar(100))
tbl#Teachers(id int,name nvarchar(100))

This code is not correct but discuss my purpose

declare @b nvarchar(100)
set @b='TBL#Students'
declare @a nvarchar(100)
set @a= 'select * from '+@b
exec @a
//Error : Could not find stored procedure 'select * from TBL#Motamem'.

What is the correct code?

Try this:

exec(@a);

If the parentheses are omitted, sql-server will consider @a as a stored procedure.

Add parenthesis after exec:

declare @b nvarchar(100) 
set @b='alerts' 
declare @a nvarchar(100) 
set @a= 'select * from '+@b 
exec (@a )

先前答案的替代方法是:

Exec sp_executesql @a

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