Perform dynamic SQL EXEC SQL SERVER

: SQL statement can be executed with ordinary Exec 

EG: the Select * from tableName 
         Exec ( ' SELECT * from tableName ' ) 
         Exec the sp_executesql N ' SELECT * from tableName '     - Note that the string must be added before the N 

2 : field name, table name , the database name of the class as a variable, dynamic must be the SQL 

EG:   
DECLARE @fname VARCHAR ( 20 is )
 SET @fname = ' FiledName ' 
the Select @fname from tableName - error, an error does not, but the result is a fixed value FiledName, not to be. 
Exec ( ' SELECT ' + + @fname 'tableName from ' ) - Note that the front and rear sides of the single quotation marks plus spaces 

will of course change the string variable may 
declare @fname VARCHAR ( 20 is )
 SET @fname = ' FiledName ' - Set field name 

declare VARCHAR @s ( 1000 )
 SET @s = ' SELECT ' + @fname + ' from tableName ' 
Exec (@s)                 - success 
Exec the sp_executesql @s    - sentence being given 



DECLARE @s Nvarchar ( 1000 ) - Note here to nvarchar ( 1000 ) 
 SET @s = 'SELECT ' + @fname + ' from tableName ' 
Exec (@s)                 - Success      
Exec the sp_executesql @s    - sentence correctly 

3 . Output parameters 
DECLARE @num int , 
        @sqls nvarchar ( 4000 )
 SET @ sqls = ' SELECT COUNT ( *) from tableName ' 
exec (@sqls)
 - how exec execution result into variables? 

@num DECLARE 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 www.cnblogs.com/fanfan-90/p/12559940.html