動態SQL(章節摘要),動態sql章節摘要

來源:互聯網
上載者:User

動態SQL(章節摘要),動態sql章節摘要
1,使用動態SQL可以在依賴對象不存在時建立子程式。


2,動態SQL主要利用EXECUTE IMMEDIATE語句執行DML,DDL,DCL等語句操作。


3,如果使用了綁定變數,則必須在EXECUTE IMMEDIATE中使用USING子句設定所需要的綁定變數。


4,使用RETURNING或RETURN語句可以接收查詢或更新後的返回結果。


5,使用批處理可以一次性將資料庫中取回的多個資料儲存在集合裡,或者使用FORALL將多個綁定參數設定到動態SQL中。
sql動態實現行列轉換

題:假設有張學產生績表(tb)如下:
姓名 課程 分數
張三 語文 74
張三 數學 83
張三 物理 93
李四 語文 74
李四 數學 84
李四 物理 94
想變成(得到如下結果):
姓名 語文 數學 物理
---- ---- ---- ----
李四 74 84 94
張三 74 83 93
-------------------
*/

create table tb(姓名 varchar(10) , 課程 varchar(10) , 分數 int)
insert into tb values('張三' , '語文' , 74)
insert into tb values('張三' , '數學' , 83)
insert into tb values('張三' , '物理' , 93)
insert into tb values('李四' , '語文' , 74)
insert into tb values('李四' , '數學' , 84)
insert into tb values('李四' , '物理' , 94)
go

--SQL SERVER 2000 靜態SQL,指課程只有語文、數學、物理這三門課程。(以下同)
select 姓名 as 姓名 ,
max(case 課程 when '語文' then 分數 else 0 end) 語文,
max(case 課程 when '數學' then 分數 else 0 end) 數學,
max(case 課程 when '物理' then 分數 else 0 end) 物理
from tb
group by 姓名

--SQL SERVER 2000 動態SQL,指課程不止語文、數學、物理這三門課程。(以下同)
declare @sql varchar(8000)
set @sql = 'select 姓名 '
select @sql = @sql + ' , max(case 課程 when ''' + 課程 + ''' then 分數 else 0 end) [' + 課程 + ']'
from (select distinct 課程 from tb) as a
set @sql = @sql + ' from tb group by 姓名'
exec(@sql)
 
動態SQL語句中對於where的一個問題

sp_executesql後面第一個參數是sql語句,必須是ntext/nchar/nvarchar類型,所以給@strSQL 賦值時,字串前面要加N;
sp_executesql後面第二個參數是內部參數表,將SQL語句中所有用到的參數寫在一個字串裡,用逗號隔開;
sp_executesql後面第三個參數開始,是外部參數,需要與內部參數表中一一對應,如果是輸出參數,需要帶outupt。
因此,完整的語句如下:
--用sp_executesql執行動態sql,適用於sql server 2005及以上declare @strSQL nvarchar(max);declare @shuju1 nvarchar(10)=N'test';declare @ID int;declare @mingcheng nvarchar(10)='aa';set @strSQL =N'select @ID = ID from ##'+@mingcheng+' where '+@mingcheng+'=@shuju1';exec sp_executesql @StrSQL, N'@ID int output,@shuju1 nvarchar(10)', @ID output, @shuju1;select @ID;
 

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.