Dynamic SQL Statement 1: Common SQL statements can be executed using Exec
Eg: Select * from tableName
Exec ('select * from tablename ')
Sp_executesql N 'select * from tablename' -- note that N must be added before the string
2: When the field name, table name, database name and so on are used as variables, dynamic SQL must be used
Eg:
Declare @ fname varchar (20)
Set @ fname = '[name]'
Select @ fname from sysobjects -- error
Exec ('select' + @ fname + 'from sysobjects') -- note that spaces must be added to the side of the single quotation mark before and after the plus sign.
Exec sp_executesql N 'select' + @ fname + 'from sysobjects'
Of course, you can also change the string to a variable.
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 that this is changed to nvarchar (1000)
Set @ s = 'select' + @ fname + 'from sysobjects'
Exec (@ s) -- Successful
Exec sp_executesql @ s -- this sentence is correct,
3: output parameters
Eg:
Declare @ num,
@ Sqls
Set @ sqls = 'SELECT count (*) from '+ @ servername +'. a. dbo. B'
Exec (@ sqls)
How can I save the exec execution result to the 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 output', @ num output
Select @ num