在某处有“脚本表作为 - MERGE”功能吗?

时间:2011-03-09 00:11:31

标签: sql-server-2008 scripting merge ssms

在SSMS 2008 R2中,当我右键单击某个表时,我看到“脚本表为”,然后是“插入和更新”选项。但是Merge怎么样?合并实际上只是其中的两个。

我可以获得任何可以添加该选项的工具吗? (所以我可以编写一个合并语句脚本,以便我添加源信息(类似于插入和更新脚本已准备好添加要插入或更新的数据)。

2 个答案:

答案 0 :(得分:3)

SSMS中没有执行此类操作的内置功能(我想可能是通过外部插件实现的。)

有一个由MichałGołoś编写的程序sp_GenMerge(已获得MIT许可),该程序允许使用数据脚本表作为合并语句。

示例场景:

CREATE TABLE [Customer]  (
   ID                   INT                  IDENTITY(1,1) CONSTRAINT PK_CUSTOMER PRIMARY KEY (ID),
   FIRSTNAME            NVARCHAR(30)         NOT NULL,
   LASTNAME             NVARCHAR(30)         NOT NULL,
   CITY                 NVARCHAR(30)         NULL,
   COUNTRY              NVARCHAR(30)         NULL,
   PHONE                NVARCHAR(20)         NULL
);

INSERT INTO [Customer] ([FirstName],[LastName],[City],[Country],[Phone])
VALUES('John','Smith','Berlin','Germany','12345'),('Cathrine','Fa','Brasilia','Brasil','(3) 4324-4723');

基本SP调用(它支持更多选项-请参阅文档)

EXEC sp_GenMerge @source_table = 'dbo.Customer';

输出:

DECLARE @xml XML = N'
<!-- Insert the generated data here -->
';


MERGE INTO dbo.Customer AS Target
USING (SELECT x.value('(@ID)', 'int') AS [ID]
            , x.value('(@FIRSTNAME)', 'nvarchar(30)') AS [FIRSTNAME]
            , x.value('(@LASTNAME)', 'nvarchar(30)') AS [LASTNAME]
            , x.value('(@CITY)', 'nvarchar(30)') AS [CITY]
            , x.value('(@COUNTRY)', 'nvarchar(30)') AS [COUNTRY]
            , x.value('(@PHONE)', 'nvarchar(20)') AS [PHONE]
        FROM @xml.nodes('v') AS t(x)) AS Source ([ID], [FIRSTNAME], [LASTNAME], [CITY], [COUNTRY], [PHONE])
  ON (Target.[ID] = Source.[ID])
WHEN NOT MATCHED BY TARGET
THEN INSERT([FIRSTNAME]
          , [LASTNAME]
          , [CITY]
          , [COUNTRY]
          , [PHONE])
     VALUES(Source.[FIRSTNAME]
          , Source.[LASTNAME]
          , Source.[CITY]
          , Source.[COUNTRY]
          , Source.[PHONE])
WHEN MATCHED AND EXISTS (SELECT Target.[FIRSTNAME]
                              , Target.[LASTNAME]
                              , Target.[CITY]
                              , Target.[COUNTRY]
                              , Target.[PHONE]
                         EXCEPT
                         SELECT Source.[FIRSTNAME]
                              , Source.[LASTNAME]
                              , Source.[CITY]
                              , Source.[COUNTRY]
                              , Source.[PHONE])
THEN UPDATE SET Target.[FIRSTNAME] = Source.[FIRSTNAME]
              , Target.[LASTNAME] = Source.[LASTNAME]
              , Target.[CITY] = Source.[CITY]
              , Target.[COUNTRY] = Source.[COUNTRY]
              , Target.[PHONE] = Source.[PHONE];
GO

并将脚本化的行作为XML有效负载:

<v ID="1" FIRSTNAME="John" LASTNAME="Smith" CITY="Berlin" COUNTRY="Germany" PHONE="12345" />
<v ID="2" FIRSTNAME="Cathrine" LASTNAME="Fa" CITY="Brasilia" COUNTRY="Brasil" PHONE="(3) 4324-4723" />

答案 1 :(得分:0)

直到我知道你不能,但有一些提示:

How to edit SSMS Script Table As templates?