此範例同
[SQL] OUTPUT 語法,差別在於 OUPUT 與法是假如 StockQty 內產品一定存在,而 Merge 則是不一定存在,且庫存量為 0 時,必須把產品刪除,藉此練習 OUTPUT 和 Merge 語法
下列在 AdventureWorks 中利用產品(Production)、庫存量(StockQty)和入領料(Stock、StockDetail)來說明 Merge 語法
- 建立基礎 Table 並插入 Sample Data
IF OBJECT_ID('StockQty') IS NOT NULL
DROP TABLE StockQty
IF OBJECT_ID('Stock') IS NOT NULL
DROP TABLE Stock
IF OBJECT_ID('StockDetail') IS NOT NULL
DROP TABLE StockDetail
IF OBJECT_ID('Production') IS NOT NULL
DROP TABLE Production
CREATE TABLE Production (ProdID int Primary key, ProdName nchar(50))
INSERT INTO Production VALUES(1,N'SQL Server 2014')
INSERT INTO Production VALUES(2,N'SQL Server 2012')
INSERT INTO Production VALUES(3,N'SQL Server 2008 R2')
INSERT INTO Production VALUES(4,N'SQL Server 2008')
INSERT INTO Production VALUES(5,N'SQL Server 2005')
-- StockQty 沒有任何資料,當 StockDetail 有資料時,
-- 會透過 Merge 語法來 insert、update 和 delete StockQty Table 內資料
CREATE TABLE StockQty (ProdID int Primary key, Qty int)
CREATE TABLE Stock (SID int Primary key, [Date] date)
CREATE TABLE StockDetail (SID int Primary key(SID,ProdID), ProdID int , Qty int)
GO