插入...不重复时选择

时间:2016-05-19 15:41:52

标签: sql sql-server tsql insert exists

我有一个触发器,它将值从一个表(OriginalTable)复制到另一个表(ChangesDuplicate)。这工作正常,但如果nameage列与插入的列不同(具有相同的some_id值,我怎么才能应用它?基本上我想确保只每name插入agesome_id的更改值。我在下面的代码在触发时仍会插入重复项。

BEGIN   
    INSERT INTO dbo.ChangesDuplicate ( 
                [some_id], 
                [name], 
                [age]
            )   SELECT
                [some_id], 
                [name], 
                [age]    
    FROM        dbo.OriginalTable    

    WHERE NOT EXISTS(SELECT [some_id]
                FROM dbo.OriginalTable ot
                WHERE ot.[some_id] = [staff_id] AND
                      ot.[name] = [name] AND
                      ot.[age] = [age]
                )
    END

由于

4 个答案:

答案 0 :(得分:0)

  

这样工作正常,但是如果名称和年龄列与插入的不同(具有相同的some_id值,我怎么能只应用它?基本上我想确保只插入每个名称和年龄的更改值) SOME_ID

你应该使用Inserted虚拟表,它可以访问新插入的行并根据你的参数进行连接。你在没有任何值的触发器中使用原始表两次

下面的代码会将行插入到changedduplicate中,如果有任何新行插入到原始表中(假设触发器在此处)并且与原始表的年龄和名称匹配(您可以根据需要添加其他条件)

INSERT INTO dbo.ChangesDuplicate ( 
                [some_id], 
                [name], 
                [age]
            )  
 SELECT
                [some_id], 
                [name], 
                [age]    
    FROM        dbo.OriginalTable  Ort  
                join
                inserted i
                on i.age<>Ort.name
                and i.name<>Ort.name

您也可以使用不存在

 Insert into changesduplicate
    select * from inserted I 
    where not exists
    (select 1 from original o where o.name=i.name and o.age=i.age)

答案 1 :(得分:0)

根据您的条件将not exists更改为exists

INSERT INTO dbo.ChangesDuplicate ( 
            [some_id], 
            [name], 
            [age]
        )   SELECT
            [some_id], 
            [name], 
            [age]    
FROM        dbo.OriginalTable o   
WHERE EXISTS (SELECT [some_id]
              FROM dbo.ChangesDuplicate dt
              WHERE dt.[some_id] = o.[staff_id] AND
                    dt.[name] <> o.[name] AND
                    dt.[age] <> o.[age]
             )

答案 2 :(得分:0)

在触发器中,你应该1)使用android:windowSoftInputMode="adjustPan" 和/或inserted个虚拟表 内部触发器中deleted的插入如下所示:

ChangesDuplicate

完整的工作示例:

INSERT INTO dbo.ChangesDuplicate ( 
            [some_id], 
            [name], 
            [age]
        )   SELECT
            [some_id], 
            [name], 
            [age]    
FROM        inserted i
    left join dbo.ChangesDuplicate cd 
       on i.some_id=cd.some_id and i.name=cd.name and i.age=cd.age --full duplicate
where cd.some_id is null --doesn't exist

答案 3 :(得分:0)

INSERT INTO dbo.ChangesDuplicate ( 
            [some_id], 
            [name], 
            [age]
        )
SELECT
    [some_id], 
    [name], 
    [age]    
FROM dbo.OriginalTable ot
LEFT JOIN dbo.ChangesDuplicate cd
    ON cd.[some_id] = ot.[some_id]
    AND cd.[name] <> ot.[name]
    AND cd.[age] <> ot.[age]