sql server触发器只更新一行

时间:2017-04-30 17:53:35

标签: sql-server tsql

我在更新后有一个触发器我想要不仅更新一行一次更新,而且还要更多行。但是当我尝试更新更多行时,错误 Subquery返回的值超过1。当子查询遵循=,!=,<,< =,>,> =或子查询用作表达式时,不允许这样做。出现。有没有办法更新更多行?

ALTER TRIGGER ChangeActorWhileUpdate
ON Herec
AFTER UPDATE
AS 
BEGIN
BEGIN TRANSACTION
BEGIN TRY

DECLARE @od DATE;
DECLARE @idHerce INT;


SELECT @idHerce = (SELECT id_herce FROM DELETED);


IF EXISTS(SELECT COUNT(*) FROM historie_hercu WHERE Herec_id_herce = @idHerce)
BEGIN

    SELECT @od = (SELECT MAX(do) FROM historie_hercu WHERE Herec_id_herce=@idHerce)

END

IF(SELECT COUNT(*) FROM historie_hercu WHERE Herec_id_herce = @idHerce) = 0
BEGIN

    SELECT @od = (SELECT datum_narozeni FROM DELETED);
END

INSERT INTO historie_hercu (jmeno_herce, prijmeni_herce, datum_narozeni, datum_umrti, mesto_narozeni, mesto_umrti, zeme, od, do, Herec_id_herce) 
SELECT jmeno_herce, prijmeni_herce, datum_narozeni, datum_umrti, mesto_narozeni, mesto_umrti, zeme, @od, CAST(GETDATE() AS DATE), @idHerce FROM DELETED;

COMMIT;
END TRY
BEGIN CATCH
PRINT ERROR_MESSAGE();
ROLLBACK;
END CATCH 
END

1 个答案:

答案 0 :(得分:1)

对于受触发操作影响的一批行触发一次触发器,每行不触发一次。您需要以能够处理多于一行的方式编写代码。

尝试类似......

ALTER TRIGGER ChangeActorWhileUpdate
ON Herec
AFTER UPDATE
AS 
BEGIN
BEGIN TRY
     BEGIN TRANSACTION; 

  WITH X AS (
    SELECT d.* , h.do AS H_Do 
          ,ROW_NUMBER() OVER (PARTITION BY h.Herec_id_herce ORDER BY do DESC) rn
    FROM deleted d
    LEFT JOIN historie_hercu h ON d.id_herce = h.id_herce
    )
    INSERT INTO historie_hercu 
    (jmeno_herce, prijmeni_herce, datum_narozeni, datum_umrti
                     , mesto_narozeni, mesto_umrti, zeme, od, do, Herec_id_herce) 
    SELECT x.jmeno_herce, x.prijmeni_herce, x.datum_narozeni, x.datum_umrti
         , x.mesto_narozeni , x.mesto_umrti, x.zeme
         , ISNULL(x.H_Do ,x.datum_narozeni)  
         , CAST(GETDATE() AS DATE), x.id_herce 
    FROM x
    WHERE x.rn = 1;

    COMMIT TRANSACTION;
END TRY

BEGIN CATCH

        PRINT ERROR_MESSAGE();
        ROLLBACK TRANSACTION;

END CATCH 
END