sql| Beginner | dynamic | grammar | statement
1: Normal SQL statements can be executed with exec
Eg:select * FROM TableName
Exec (' SELECT * FROM TableName ')
Exec sp_executesql n ' select * FROM tablename '-Note that you must add n before the string
2: Field name, table name, database name, etc. as variables, you must use dynamic SQL
eg
DECLARE @fname varchar (20)
Set @fname = ' Filedname '
Select @fname from TableName-error, does not prompt an error, but the result is a fixed value filedname, not desired.
Exec (' select ' + @fname + ' from tablename ')--pay attention to the margin of the single quotation mark before and after the plus space
Of course, the form of changing a string to a variable can also
DECLARE @fname varchar (20)
Set @fname = ' Filedname '--set field name
DECLARE @s varchar (1000)
Set @s = ' SELECT ' + @fname + ' from tablename '
Exec (@s)--Successful
EXEC sp_executesql @s--This sentence will be an error
DECLARE @s Nvarchar (1000)--note here to Nvarchar (1000)
Set @s = ' SELECT ' + @fname + ' from tablename '
Exec (@s)--Successful
EXEC sp_executesql @s--the correct sentence
3. Output parameters
DECLARE @num int,
@sqls nvarchar (4000)
Set @sqls = ' SELECT count (*) from TableName '
EXEC (@sqls)
--How do I put exec execution results 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
Also, if you want to use single quotes ' to use ' in SQL statement strings