触发器执行时,子查询返回的值超过1

时间:2018-05-08 13:02:28

标签: sql-server

我有一个触发器,它在另一个表中的字段更改时将日志条目添加到表中。它在更改一行时有效,但在多行更改时出错。那里的任何人都能够解释我必须做些什么来使我的触发器也能用于多行更新?

非常感谢,

德里克

Declare @PropertyID uniqueidentifier

    Set @PropertyID = (Select CONVERT(VARCHAR( 36 ), ISNULL(i.[PropertyPK], d.[PropertyPK]))
    FROM 
        INSERTED i 
    FULL OUTER JOIN DELETED d ON ( d.[PropertyPK] = i.[PropertyPK] )

    WHERE 
        ( d.[strManagingOfficeName] <> i.[strManagingOfficeName] ) OR
        ( d.[strManagingOfficeName] IS NULL AND i.[strManagingOfficeName] IS NOT NULL ) OR
        ( i.[strManagingOfficeName] IS NULL AND d.[strManagingOfficeName] IS NOT NULL ))

    Declare @CompanyID uniqueidentifier

    Set @CompanyID = (Select CompanyFK From Property Where PropertyPK = @PropertyID)

    --Deleted Old Ones

    Delete From TDSAPILog Where ObjectFK = @PropertyID And strObject = 'Branch Change'

    --Insert New Log

    INSERT dbo.TDSAPILog(TDSAPILogPK, ObjectFK, strObject, strStatus, CompanyFK, dteDateLogged)
    SELECT
        NewID(),
        @PropertyID,
        'Branch Change',
        'Active',
        @CompanyID ,
        GetDate()

1 个答案:

答案 0 :(得分:1)

当您从查询返回多个值并保存在变量中或与where子句中的值进行比较时,会发生此错误。

在您的示例中,我认为错误发生在此行

SET @CompanyID = (SELECT CompanyFK FROM Property WHERE PropertyPK = @PropertyID)

要解决报告的错误,只需在查询中输入“TOP 1”即可。示例如下所示:

SET @CompanyID = (SELECT TOP 1 CompanyFK FROM Property WHERE PropertyPK = @PropertyID)

在以下情况下,子查询返回的值可能超过1:

SET @YouVariable = (SELECT ColumnID FROM yourTable WHERE Identity = @SomeValue)

-- if the above query return more than 1 value the same error will be occurred
-- to resolve this problem just put "TOP 1" before ColumnID  

SELECT * 
FROM OtherTable 
WHERE OtherIdentity = ((SELECT ColumnID FROM yourTable 
                        WHERE Identity = @SomeValue))

-- if the above query return more than 1 value the same error will be occurred
-- to resolve this problem just replace "= with IN()". Example give below
SELECT * 
FROM OtherTable 
WHERE OtherIdentity IN ((SELECT ColumnID FROM yourTable 
                         WHERE Identity = @SomeValue))