我在SQL Server 2000的表中有一个触发器,这是触发器:
ALTER Trigger [dbo].[Set_Asignado_State] ON [dbo].[Tables]
FOR INSERT AS
BEGIN
DECLARE @area varchar(1)
SELECT @area = Table_Area_ID FROM inserted
IF (@area = 'L')
BEGIN
INSERT INTO Table_History
SELECT (SELECT TOP 1 Table_Area_Id AS Table_Area_Id FROM inserted) AS Table_Area_Id,
(SELECT SUBSTRING( CAST( YEAR( GETDATE() ) AS VARCHAR), 3, 2) ) AS Table_Year,
(SELECT TOP 1 Table_Seq AS Table_Seq FROM inserted) AS Table_Seq,
(SELECT TOP 1 ID FROM Table_Status WHERE Description = 'Asignado') AS Status,
'' AS Responsible,
(SELECT TOP 1 OrigDept FROM inserted) AS User_Responsible,
GETDATE() AS [DateTime],
'None' AS Comments
FROM Tables
WHERE Tables.Table_Area_Id = (SELECT TOP 1 Table_Area_Id AS Table_Area_Id FROM inserted) AND
Tables.Table_Year = (SELECT SUBSTRING(CAST(YEAR(GETDATE()) AS VARCHAR), 3, 2) )
IF @@ERROR <> 0
BEGIN
DECLARE @errorMsg NVARCHAR(256)
SET @errorMsg = @@ERROR;
PRINT 'Error Inserting in Table_History'
END
END
END
现在,当他们在“Tables”中插入记录时,会调用触发器,但它会继续在Table_History上插入许多记录。
我和同龄人谈过,似乎没有错! = S关于这个的任何线索?难道我做错了什么?
提前致谢=)
答案 0 :(得分:0)
Table_History表上是否有另一个触发器插入到表中?
答案 1 :(得分:0)
触发器是基于设置的,所以执行
IF (@area = 'L')
只会查看插入表中的第一条记录。尝试将检查添加为WHERE子句的一部分:
WHERE Tables.Table_Area_Id = (SELECT TOP 1 Table_Area_Id AS Table_Area_Id FROM inserted) AND
Tables.Table_Year = (SELECT SUBSTRING(CAST(YEAR(GETDATE()) AS VARCHAR), 3, 2) )
AND SUBSTRING(Tables.Table_Area_Id, 1, 1) = 'L'
你确定主Select语句只返回一行吗?我注意到你已经广泛使用了Top(1)限定符。如果它返回多行,则会在历史记录表中插入多行。
也许作为盲注,尝试为最外面的选择放入Top(1):
INSERT INTO Table_History
SELECT TOP(1) (SELECT TOP 1 ...
否则看起来好像你在触发器中有一些递归。我看不到它,但如果你愿意,你可以关闭整个数据库的递归触发,因为它是一个数据库选项。