O.F。,
所以我一直在尝试构建一个触发器,它将根据在不同表中更新行的时间来更新表。到目前为止,触发器看起来像这样。
ALTER TRIGGER [dbo].[tst_update_USCATVLS_6]
ON [dbo].[IV00101]
AFTER UPDATE
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE @ITEMNUMBER VARCHAR(75)
SET @ITEMNUMBER = (SELECT ITEMNMBR FROM dbo.IV00101 WHERE DEX_ROW_TS = (SELECT MAX(DEX_ROW_TS) FROM dbo.IV00101))
UPDATE dbo.EXT00101 SET STRGA255 = (RTRIM(LTRIM(STRGA255))) + '_0' WHERE PT_UD_KEY = @ITEMNUMBER AND PT_UD_Number = 2
当我运行如下所示的测试更新时,似乎会发生什么。
UPDATE PDM.TEST.dbo.IV00101
SET USCATVLS_6 = 'OBSOLETE'
WHERE ITEMNMBR = 'HMLGDN-7563252-4'
是触发器触发但是两次更新所需的列。最终结果是这个20025947756319_0_0而不是20025947756319_0。
所有这一切的奇怪之处在于,如果我删除触发器并运行相同的测试更新,然后运行触发器中的所有语句执行的更新语句,并根据需要更新数据。
因此,将此作为一个代码块运行:
UPDATE PDM.TEST.dbo.IV00101
SET USCATVLS_6 = 'OBSOLETE'
WHERE ITEMNMBR = 'HMLGDN-7563252-4'
DECLARE @ITEMNUMBER VARCHAR(75)
SET @ITEMNUMBER = (SELECT ITEMNMBR FROM PDM.TEST.dbo.IV00101 WHERE DEX_ROW_TS = (SELECT MAX(DEX_ROW_TS) FROM PDM.TEST.dbo.IV00101))
UPDATE PDM.TEST.dbo.EXT00101 SET STRGA255 = (RTRIM(LTRIM(STRGA255))) + '_0' WHERE PT_UD_KEY = @ITEMNUMBER AND PT_UD_Number = 2
如果有人能帮我弄清楚为什么会这样,我会非常感激。
最诚挚的问候, Z.
答案 0 :(得分:0)
阅读了Sean Lange的评论后,我查了一下插入并删除了表格。我之前看过这些表的引用,但没有意识到它们是临时表,并且认为它们是我看到的示例/答案中数据库的物理表。无论如何,我创建了一个触发器来显示每个数据,这有助于我了解如何将它们连接到触发器中的update语句。所有代码都在下面。
触发查看Inserted和Deleted中的内容以及引用Inserted表的连接:
ALTER TRIGGER [dbo].[inserted_deleted_Table]
ON [dbo].[IV00101]
AFTER UPDATE
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
select 'NEW DATA', * from inserted --new data
select 'OLD Data', * from deleted --old data
select 'iv00101', * From iv00101 as i JOIN inserted as u on i.itemNmbr = u.itemNmbr and i.DEX_ROW_TS = u.DEX_ROW_TS
-- Insert statements for trigger here
END
最终解决方案是删除这段代码:
SET @ITEMNUMBER = (SELECT ITEMNMBR FROM INV00101 WHERE DEX_ROW_TS = (SELECT MAX(DEX_ROW_TS) FROM INV00101 ) AND USCATVLS_6 ='OBSOLETE' )
然后将FROM子句添加到UPDATE语句:
UPDATE PDM.TEST.dbo.EXT00101 SET STRGA255 = (RTRIM(LTRIM(STRGA255))) + '_0'
FROM (
SELECT u.ITEMNMBR ,
u.DEX_ROW_TS
From iv00101 as i JOIN inserted as u on i.itemNmbr = u.itemNmbr and i.DEX_ROW_TS = u.DEX_ROW_TS) as p
WHERE PT_UD_KEY = p.ITEMNMBR AND PT_UD_Number = 2
一旦我发现插入和删除的表是临时表而不是数据库中的实际表,所有的部分sorta就到位了。谢谢你指点我需要去@Sean Lange的方向。
最诚挚的问候, ž。