SQL Server:基于ID更新值,而无需插入表中

时间:2019-01-10 10:41:12

标签: sql sql-server tsql triggers

ALTER TRIGGER MyTrigger 
ON persons 
AFTER INSERT
AS 
    IF EXISTS(SELECT * 
              FROM Persons t 
              INNER JOIN inserted i ON i.LastName <> t.LastName 
                                    OR i.FirstName <> t.FirstName 
                                    OR i.address <> t.address 
                                    OR i.City <> t.City 
                                    AND i.PersonID = t.PersonID) 
    BEGIN
        UPDATE p 
        SET p.LastName = i.LastName, 
            p.FirstName = i.FirstName,
            p.address = i.address,
            p.City = i.City
        FROM persons AS p
        INNER JOIN inserted i ON p.PersonID <> i.PersonID
        WHERE p.PersonID = i.PersonID 
    END

当我尝试插入具有先前ID的新列时,该行正在更新,这很好。但是我也不想插入新行

3 个答案:

答案 0 :(得分:2)

我认为您正在寻找

var cors = require('cors')

if (NODE_ENV !== 'production') {
   app.use(cors())
}
  • 用触发器的名称替换CREATE TRIGGER <Trigger Name Here> ON <Table Name Here> INSTEAD OF INSERT, UPDATE AS INSERT INTO <Table Name Here> SELECT I.* FROM INSERTED I INNER JOIN <Table Name Here> T ON I.ID <> T.ID; --Insert all rows with the ID does not exists in the table UPDATE T SET T.FirstName = I.FirstName, T.LastName = I.LastName, T.Address = I.Address, T.City = I.City FROM INSERTED I INNER JOIN <Table Name Here> T ON T.ID = I.ID --UPDATE all rows with the same ID already exists in the table WHERE T.FirstName <> I.FirstName AND --OR T.LastName <> I.LastName AND --OR T.Address <> I.Address AND --OR T.City <> I.City;
  • 用表名替换<Trigger Name Here>

答案 1 :(得分:1)

我认为您应该学习如何使用merge而不是在触发器中执行此逻辑。但是,您的问题是有关如何使触发器起作用的。您想要的是一个触发器来代替插入,而不是随后运行。

您需要在触发器内插入 。看起来像:

ALTER TRIGGER MyTrigger ON persons INSTEAD OF INSERT
AS 
BEGIN
    -- Insert person ids that are new
    INSERT INTO persons
        SELECT i.*
        FROM inserted i
        WHERE NOT EXISTS (SELECT 1
                          FROM persons p
                          WHERE i.PersonID = p.PersonID
                         );

    -- update existing person ids
    UPDATE p 
        SET p.LastName = i.LastName, 
            p.FirstName = i.FirstName,
            p.address = i.address,
            p.City = i.City
        FROM persons p INNER JOIN
             inserted i
             ON p.PersonID = i.PersonID
        WHERE p.LastName <> i.LastName OR 
              p.FirstName <> i.FirstName OR
              p.address <> i.address OR
              p.City <> i.City;
END;  -- MyTrigger

我已经离开了您所拥有的比较条件,尽管我认为它们不正确。您需要非常注意NULL的值。如果任何旧值或新值均为NULL,则不会发生UPDATE

答案 2 :(得分:0)

为什么不尝试使用这样的存储过程

 create stored procedure USP_UpsertPerson
(
    @personId
    @ other inputsinputs
)


AS 
BEGIN
 IF( @personId IS NOT NULL)
BEGIN
 ----------- here Update table script With @personId
END
ELSE
BEGIN
   ----------- here Insert table script
END
END 
GO

然后,当您要插入@personId时将其发送为null,并在其希望更新时将其发送给

执行比查询快,易于引用代码且工作正常