SQL output子句的用法

來源:互聯網
上載者:User

以上是表soloreztest的原始內容使用output子句對其進行操作

A. 將 OUTPUT INTO 用於簡單 INSERT 語句

   以下樣本將行插入soloreztest表,並使用 OUTPUT 子句將語句的結果返回到 @mytable table 變數中
 declare @mytable table
(
  id int identity(1,1) primary key,
  name varchar(50)
)
 insert into soloreztest output inserted.name into @mytable values('147')
select * from soloreztest
select * from @mytable

結果是:
 

  output    into子句是將向soloreztest表裡面的資料同步的插入的@mytable的表變數裡面
  output 子句則只是用於顯示被改變的資料INSERTED 或 DELETED 首碼
  inserted 首碼:用於檢索新插入表中或是更新後的資料的資料 可用與insert和update語句中不能在delete語句中出現
  deleted 首碼: 用於檢索被刪除或是更新前的資料 可用與delete和update語句中不能在insert 語句中出現

 B. 將 OUTPUT 用於 DELETE 語句
   以下執行個體是將在表中soloreztest刪除行是放回被刪除行的資訊
     delete soloreztest  output deleted.* where id=2
  

 

 同理以上也可使用會 output into語句將被刪除的資訊插入到一個新表中

 C. 將 OUTPUT  用於 UPDATE
 以下執行個體將在表中更新資料是使用output 返回修改前的資料和修改後的資料
update soloreztest   set name='zz' output  inserted.name,deleted.name where id=3
 
inserted.name:表示的是在 soloreztest表中更新後的資料內容。
deleted.name :表示的是在soloreztest表中的更新前的資料內容。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.