在.NET应用程序中忽略T-SQL触发器中的错误

时间:2014-05-02 19:57:30

标签: c# sql .net sql-server

我有一个TableAdapter,我正在调用适配器的Update(DataSet dataset)功能。基础表上有一个触发器抛出一个错误,但是这个错误在select语句之后没有在应用程序中引起异常,但是如果我只是在触发器的开头引发它就会导致异常。有什么想法吗?

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE TRIGGER [dbo].[trigger1] 
   ON  [dbo].[table1]
   AFTER INSERT, UPDATE
AS

SET NOCOUNT ON;

SELECT a.description
FROM table1 a
INNER JOIN table2 b ON b.b_id = a.b_id
INNER JOIN inserted i ON i.b_id = a.b_id AND i.a_id = a.a_id
WHERE a.code = i.code
AND b.b_id <> i.b_id
AND a.description <> i.description
AND b.code IN (SELECT code FROM b WHERE b_id = i.b_id)

IF (@@ROWCOUNT > 0)
BEGIN
    RAISERROR ('ERROR', 16, 1)
    ROLLBACK TRAN
    RETURN
END

GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO 

1 个答案:

答案 0 :(得分:1)

您似乎正在检查@@ROW_COUNT以测试是否存在冲突的行。也许EXISTS查询可以满足您的需求:

IF EXISTS (
    SELECT a.description
    FROM table1 a
    INNER JOIN table2 b ON b.b_id = a.b_id
    INNER JOIN inserted i ON i.b_id = a.b_id AND i.a_id = a.a_id
    WHERE a.code = i.code
    AND b.b_id <> i.b_id
    AND a.description <> i.description
    AND b.code IN (SELECT code FROM b WHERE b_id = i.b_id)
)
BEGIN
    RAISERROR ('ERROR', 16, 1)
    ROLLBACK TRAN
    RETURN
END

如果仍未提出错误,那么业务逻辑值得仔细研究。