動態語句基本語法:
1 :普通SQL語句可以用exec執行
Select * from tableName exec('select * from tableName')
exec sp_executesql N'select * from tableName' -- 請注意字符串前一定要加N
2:字段名,表名,數據庫名之類作為變量時,必須用動態
SQL 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 -- 此句正確