SQL Server 2012 - 動態SQL查詢

動態SQL的兩種執行方式:EXEC @sql 和 EXEC sys.sp_executesql @sqlsql

DECLARE @c_ids VARCHAR(200)
SET @c_ids ='1,2'

--直接這樣是沒法執行的
--SELECT * FROM dbo.Student WHERE Class IN (@c_ids)

--1, Exec 執行SQL動態查詢
Exec  ('SELECT * FROM dbo.Student WHERE Class IN ('+@c_ids+')')

-- 2,經過動態查詢,過濾須要的列
DECLARE @rols VARCHAR(200)
SET @rols='StuName,StuAge,Class'
Exec  ('SELECT '+@rols+' FROM dbo.Student WHERE Class IN ('+@c_ids+')')

--3,執行SQL動態查詢的另一種方法,經過內置存儲過程:sys.sp_executesql 執行SQL語句
DECLARE @sql NVARCHAR(200)
SET @sql='SELECT '+@rols+' FROM dbo.Student WHERE Class IN ('+@c_ids+')'
EXEC sys.sp_executesql @sql

--4, 存儲過程動態執行SQL,以參數變量@agePara的形式給SQL語句傳遞變量
DECLARE @age INT
SET @age = 18
SET @sql='SELECT * FROM dbo.Student WHERE StuAge = @agePara '
EXEC sys.sp_executesql @sql,N'@agePara  int',@age 
 
--5, '' 兩個' 轉移成一個',選擇出名字中包含有‘英’字的學生信息
DECLARE @txt NVARCHAR(10)
SET @txt = '英'
SET @sql='SELECT *  FROM dbo.Student WHERE StuName like ''%@namePara'' '
EXEC sys.sp_executesql @sql,N'@namePara   NVARCHAR(10)',@txt 

--6, 把須要輸出的變量一樣能夠定義到變量中進行輸出
DECLARE @rowCountResult INT
SET @sql='SELECT @rowCountResult=count(*) FROM dbo.Student WHERE StuAge = @agePara '
EXEC sys.sp_executesql @sql,N'@agePara  int,@rowCountResult int OutPut',@age ,@rowCountResult OUTPUT
SELECT @rowCountResult


--7,技巧:用Print 查看拼接的動態SQL是否正確
SELECT 'SELECT '+@rols+' FROM dbo.Student WHERE StuAge = @agePara '
相關文章
相關標籤/搜索