Basic syntax of dynamic SQL statements
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 field names, table names, database names, etc. are used as variables, dynamic SQL must be used
eg:
declare @fname varchar(20)
set @fname = 'FiledName'
Select @fname from tableName -- Error, no error will be prompted, but the result is a fixed value FiledName, which is not what you want.
Exec('select ' + @fname + ' from tableName') -- Please note that there are spaces around the single quotes before and after the plus sign.
Of course, you can also change the string into a variable form
declare @fname varchar(20)
set @fname = 'FiledName' --Set the 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)
set @s = 'select ' + @fname + ' from tableName'
Exec(@s) -- success
exec sp_executesql @s -- This sentence is correct
3. Output parameters
declare @num int,
@sqls nvarchar(4000)
set @sqls='select count(*) from tableName'
exec(@sqls)
--How to put the exec execution result 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
If you want to use single quotes '' in the SQL statement string, you can use ''''