1: Ordinary SQL statement can be performed with EG: SELECT * from Tablename EXEC ('Select * from tablename ") sp_executesql n'select * from tablename' - Please pay attention to the string must add N
2: Field name, table name, database name as variables, must be used as a variable, you must use dynamic SQLEG: Declare @fname varchar (20) set @fname = '[name]' select @fname from sysobjects - Error EXEC ('SELECT' @fname 'from sysobjects' - Please note that the edge of the single quotes before and after adding the sparks exec sp_executesql n 'select' @fname 'from sysobject', of course, the string is changed to variables. Declare @s varchar (1000) set @s = 'select' @fname 'from sysobjects' exec (@s) - successful exec sp_executesql @S - This sentence will report an error
Declare @s nvarchar (1000) - Note here to nvarchar (1000) set @S = 'SELECT' @fname 'from sysobjects' exec (@s) - successful exec sp_executesql @S - This sentence is correct ,
3: Output parameter EG: Declare @num, @sqlsset @ SQLS = 'select count (*) from' @servername '.a.dbo.b'Exec (@sqls) I can put the result of Exec Variable @num
Declare @num int, @sqls nvarchar (4000) set @ SQLS = 'select @ a = count (*) from' @servername .a.dbo.b'Exec sp_executesql @ SQLS, N' @ a int outprut ', @num outstselect @num