Stored procedures use dynamic table names

-- When the field name, table name and database name are used as variables, dynamic sql must be used 
-- 1: Ordinary SQL statements can be executed with Exec eg:   

Select  *  from tableName         
 Exec ( ' select * from tableName ' )          
 Exec sp_executesql N ' select * from tableName '     
-- please note that N must be added before the string

-- 2: When the field name, table name, database name, etc. are used as variables, dynamic SQL must be used eg: declare @fname varchar(20) 
set  @fname  =  ' FiledName '  
Select  @fname  from tableName              
 -- error, no prompt Error, but the result is a fixed value of FiledName, which is not desired.

Exec ( ' select '  +  @fname  +  ' from tableName ' )     
 -- please note that spaces are added around the single quotes before and after the plus sign. Of course, the string can be changed into a variable form, and you can also 
declare  @fname  varchar ( 20 ) 
 set  @fname  =  ' FiledName '  
-- set field name 
declare  @s  varchar ( 1000 ) 
 set  @s  =  ' select '  +  @fname  +  ' from tableName '  
Exec ( @s)                
 --success _

exec sp_executesql @s    
-- this sentence will report an error

declare  @s  Nvarchar ( 1000 )  
 -- note that it is changed to nvarchar ( 1000 ) here 
set  @s  =  ' select '  +  @fname  +  ' from tableName '  
Exec ( @s )                
 -- success     

exec sp_executesql @s    
-- this sentence is correct

3. 输出参数 
declare @num int,   @sqls nvarchar(4000) 
set @sqls='select count(*) from tableName' 
exec(@sqls) 

--How to put the result of exec execution into a variable? 
declare  @num  int ,    @sqls  nvarchar ( 4000 ) 
 set  @sqls = ' select @a=count(*) from tableName ' 
exec sp_executesql @sqls ,N ' @a int output ' , @num output select  @num

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325022594&siteId=291194637