我有一个触发器,它根据INSERTED
的一个值插入到另一个表中。
CREATE TRIGGER
[dbo].[triggerTest]
ON
[dbo].[Original]
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON
If (SELECT city FROM INSERTED) = 'LA'
INSERT INTO Hotel
SELECT price, quality FROM Inserted AS I
ELSE IF (SELECT city FROM INSERTED) = 'NY'
INSERT INTO Inn
SELECT price, quality FROM Inserted AS I
END
我发现当我在Original
表中插入多行时,出现此错误:
SQL Server子查询返回了多个值。当子查询遵循=,!=,<,<=,>,> =
时,不允许这样做
上述触发器有什么问题?
答案 0 :(得分:2)
您的INSERTED
表返回了更多的行,因此,您需要top (1)
和order by
子句,但我会改为exists
:
CREATE TRIGGER [dbo].[triggerTest]
ON [dbo].[Original]
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON
IF EXISTS (SELECT 1 FROM INSERTED WHERE city = 'LA')
INSERT INTO Hotel (price, quality)
SELECT price, quality
FROM Inserted AS I
IF EXISTS (SELECT 1 FROM INSERTED WHERE city = 'NY')
INSERT INTO Inn (price, quality)
SELECT price, quality
FROM Inserted AS I
END
注意:
INSERT
操作时始终显式限定列名。