為您講解SQL動態(tài)語句的語法
動態(tài)SQL語句是SQL中相當重要的語句,下面就將為您詳細介紹動態(tài)SQL語句的語法,供您參考,希望對您能夠有所啟示。
1 :普通SQL語句可以用Exec執(zhí)行
eg: Select * from tableName
Exec('select * from tableName')
Exec sp_executesql N'select * from tableName' -- 請注意字符串前一定要加N
2:字段名,表名,數據庫名之類作為變量時,必須用動態(tài)SQL
eg:
declare @fname varchar(20)
set @fname = 'FiledName'
Select @fname from tableName -- 錯誤,不會提示錯誤,但結果為固定值FiledName,并非所要。
Exec('select ' + @fname + ' from tableName') -- 請注意 加號前后的 單引號的邊上加空格
當然將字符串改成變量的形式也可
declare @fname varchar(20)
set @fname = 'FiledName' --設置字段名
declare @s varchar(1000)
set @s = 'select ' + @fname + ' from tableName'
Exec(@s) -- 成功
exec sp_executesql @s -- 此句會報錯
declare @s Nvarchar(1000) -- 注意此處改為nvarchar(1000)
set @s = 'select ' + @fname + ' from tableName'
Exec(@s) -- 成功
exec sp_executesql @s -- 此句正確
3. 輸出參數
declare @num int,
@sqls nvarchar(4000)
set @sqls='select count(*) from tableName'
exec(@sqls)
--如何將exec執(zhí)行結果放入變量中?
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
【編輯推薦】