使用合并时不匹配时插入

时间:2017-11-04 21:07:07

标签: sql-server

我正在尝试使用MERGE将记录插入表中。 如果表中不存在EmployeeCode,则应插入新记录。

我的代码就像这样

DECLARE     @EmployeeCode           BIGINT = 1234,
            @FirstName              VARCHAR(250) = 'FirstName',
            @MiddleName             VARCHAR(250) = 'LastName',
            @LastName               VARCHAR(250) = 'LastName',
            @Nationality            VARCHAR(250) = 'Nationality',
            @BloodGroup             VARCHAR(4) = 'A+',
            @Gender                 VARCHAR(7)  = 'Male'

MERGE dbo.tbTableName AS tb1
USING ( SELECT  tbTableName.EmployeeCode
        FROM    dbo.tbTableName tbTableName
        WHERE   tbTableName.EmployeeCode    =   @EmployeeCode) AS tb2 (EmployeeCode)
ON  (tb1.EmployeeCode = tb2.EmployeeCode)
WHEN NOT MATCHED THEN
    INSERT (    EmployeeCode, FirstName, MiddleName, LastName,Nationality, BloodGroup, Gender )
    VALUES (    @EmployeeCode, @FirstName, @MiddleName, @LastName, @Nationality, @BloodGroup, @Gender );

我遇到的问题是,即使EmployeeCode与表中的任何记录都不匹配,它也不会插入。

2 个答案:

答案 0 :(得分:0)

我使用了另一种方法来解决问题,使用这样的IF语句:

{{1}}

答案 1 :(得分:0)

现在是时候阅读第一个例子的documentation研究了。该示例显示了从传统的if / else update / insert代码块到单个merge语句的转换。请注意示例中如何定义表源。您正在从表中选择一行(您知道它不存在) - 因此实际上没有行可用于插入或更新。这就是为什么没有插入的原因。合并信息的来源应该是您的变量集,就像文档示例一样。缩写版本:

set nocount on;
DECLARE     @EmployeeCode           BIGINT = 1234,
        @FirstName              VARCHAR(250) = 'FirstName',
        @MiddleName             VARCHAR(250) = 'LastName',
        @LastName               VARCHAR(250) = 'LastName',
        @Nationality            VARCHAR(250) = 'Nationality',
        @BloodGroup             VARCHAR(4) = 'A+',
        @Gender                 VARCHAR(7)  = 'Male';

declare @tbl table (EmployeeCode bigint, FirstName varchar(250)); 
--insert @tbl(EmployeeCode, FirstName) values (1234, 'zork');

MERGE @tbl AS tb1
USING ( SELECT  @EmployeeCode, @FirstName) as src(EmployeeCode, FirstName)
ON  (tb1.EmployeeCode = src.EmployeeCode)
WHEN NOT MATCHED THEN
INSERT (    EmployeeCode, FirstName )
VALUES (    @EmployeeCode, @FirstName );

select @@ROWCOUNT, * from @tbl;