天天看點

sql動态基本文法

1.基本格式

eg: Select * from tableName
Exec('select * from tableName')   

Exec sp_executesql N'select * from tableName' 
           

--請注意字元串前一定要加N

以上這三種方式都可以實作查詢。

sql動态基本文法

2.執行個體

2.1字段名,表名,資料庫名之類作為變量時,必須用動态sql

例1:字段名變更

DECLARE @b VARCHAR(50)

SET @b='b'

EXEC ('select '[email protected]+' from t1')
           

--請注意加号前後的單引号的邊上加空格

例2:字段名變更

DECLARE @b VARCHAR(50)

SET @b='b'

SELECT @b FROM t1
           

  --錯誤,不會提示錯誤,但結果為固定值b,并非所要

sql動态基本文法

例3.将字元串改成變量的形式

DECLARE @c VARCHAR(20)
SET @c='b'--設定字段名

DECLARE @s VARCHAR(1000)
SET @s='select '[email protected]+' from t1'
EXEC(@s) --成功
EXEC sp_executesql @s--此句報錯;過程需要類型為‘ntext/nchar/nvarchar'的參數'@statement'.
           
DECLARE @s nVARCHAR(1000)
SET @s='select '[email protected]+' from t1'
--EXEC(@s) --成功
EXEC sp_executesql @s --成功