Dynamic Statement Basic syntax:
1: Normal SQL statements can be executed with exec
SELECT * from TableName exec (' select * from TableName ')
EXEC sp_executesql n ' select * from TableName '--please note that the string must be added n before
2: Field name, table name, database name, etc. as variables, you must use dynamic
SQL declare @fname varchar set @fname = ' Filedname ' Select @fname from TableName-error, no error is indicated, but the result is a fixed value of filedname, not required. EXEC (' select ' + @fname + ' from TableName ')--pay attention to the space on the edge of the single quotation mark before and after the plus sign
Of course, changing the string to a variable can also
DECLARE @fname varchar Set @fname = ' Filedname '--set field name
DECLARE @s varchar (+) Set @s = ' SELECT ' + @fname + ' from TableName ' EXEC (@s)--Success
EXEC sp_executesql @s--This sentence will be error declare @s Nvarchar (1000)--note here to Nvarchar (1000)
Set @s = ' SELECT ' + @fname + ' from TableName ' EXEC (@s)--Successful exec sp_executesql @s--this sentence is correct
SQL Server Dynamic table name dynamic field name execution Dynamic SQL