我正在使用Sql Server数据库项目迈出第一步,我正在寻找一种在部署后脚本中填充引用表的方法,而不是每次都删除和重新填充它们。经过一番研究后,我偶然发现了这篇博文:
这基本上用这个例子描述了MERGE语句的行为:
-- Reference Data for AddressType
MERGE INTO AddressType AS Target
USING (VALUES
(0, N'Undefined'),
(1, N'Billing'),
(2, N'Home'),
(3, N'Main Office'),
(4, N'Primary'),
(5, N'Shipping'),
(6, N'Archive')
)
AS Source (AddressTypeID, Name)
ON Target.AddressTypeID = Source.AddressTypeID
-- update matched rows
WHEN MATCHED THEN
UPDATE SET Name = Source.Name
-- insert new rows
WHEN NOT MATCHED BY TARGET THEN
INSERT (AddressTypeID, Name)
VALUES (AddressTypeID, Name)
-- delete rows that are in the target but not the source
WHEN NOT MATCHED BY SOURCE THEN
DELETE
由于我也使用Oracle数据库,我尝试将之前的示例调整为Oracle 10g语法,并且我已经生成了这样的内容:
-- Reference Data for AddressType
MERGE INTO AddressType AS T
USING (WITH CTE AS (
SELECT 0 AS AddressTypeID, 'Undefined' AS Name FROM DUAL
UNION
SELECT 1 AS AddressTypeID, 'Billing' AS Name FROM DUAL
UNION
SELECT 2 AS AddressTypeID, 'Home' AS Name FROM DUAL
UNION
SELECT 3 AS AddressTypeID, 'Main Office' AS Name FROM DUAL
UNION
SELECT 4 AS AddressTypeID, 'Primary' AS Name FROM DUAL
UNION
SELECT 5 AS AddressTypeID, 'Shipping' AS Name FROM DUAL
UNION
SELECT 6 AS AddressTypeID, 'Archive'AS Name FROM DUAL
)
SELECT AddressTypeID, Name FROM CTE
)
AS S
ON T.AddressTypeID = S.AddressTypeID
-- update matched rows
WHEN MATCHED THEN
UPDATE SET T.Name = S.Name
-- insert new rows
WHEN NOT MATCHED
INSERT (T.AddressTypeID, T.Name)
VALUES (S.AddressTypeID, S.Name)
除了不完全等效(对于不在源中的行没有删除),我发现语法特别笨拙。
Oracle SQL有哪些语法快捷方式?
答案 0 :(得分:2)
我没有看到任何捷径, MERGE 的语法就是你所拥有的。
唯一可以摆脱的是 WITH子句,即 USING 子句中的CTE。你可以简单地把它当作:
-- Reference Data for AddressType
MERGE INTO AddressType AS T
USING (
SELECT 0 AS AddressTypeID, 'Undefined' AS Name FROM DUAL
UNION
SELECT 1 AS AddressTypeID, 'Billing' AS Name FROM DUAL
UNION
SELECT 2 AS AddressTypeID, 'Home' AS Name FROM DUAL
UNION
SELECT 3 AS AddressTypeID, 'Main Office' AS Name FROM DUAL
UNION
SELECT 4 AS AddressTypeID, 'Primary' AS Name FROM DUAL
UNION
SELECT 5 AS AddressTypeID, 'Shipping' AS Name FROM DUAL
UNION
SELECT 6 AS AddressTypeID, 'Archive'AS NAME FROM DUAL
) AS S
ON T.AddressTypeID = S.AddressTypeID
-- update matched rows
WHEN MATCHED THEN
UPDATE SET T.Name = S.Name
-- insert new rows
WHEN NOT MATCHED
INSERT (T.AddressTypeID, T.Name)
VALUES (S.AddressTypeID, S.Name)
当然,您无法更新ON
子句中提到的列。