作为一个经验很少或没有经验的用户,我必须在桌面上创建一个触发器(或找到另一个解决方案)。需要完成的是,当列ESB的值在表中的另一行中更改为“1”时,该列必须设置为“0”。
我的目的是使用AFTER UPDATE触发器来执行此操作。
ALTER TRIGGER [TR_PHOTO_UPD]
ON [SOA].[dbo].[photos_TEST]
AFTER UPDATE
AS
DECLARE @ID VARCHAR(10)
DECLARE @ESB VARCHAR(1)
SELECT @ID = (SELECT TOP(1) ID
FROM SOA.dbo.photos_TEST
WHERE esb = 'Q'
ORDER BY ARRIVALDATETIME ASC)
SELECT @ESB (SELECT esb FROM INSERTED)
IF @ESB = '1'
UPDATE SOA.dbo.photos_TEST SET esb = '0' WHERE ID = @I
您可能理解,这不起作用,也不适用于下一个触发器定义。
ALTER TRIGGER [TR_PHOTO_UPD]
ON [SOA].[dbo].[photos_TEST]
AFTER UPDATE
AS
DECLARE @ID VARCHAR(10)
DECLARE @ESB VARCHAR(1)
SELECT @ID = (SELECT TOP(1) ID
FROM SOA.dbo.photos_TEST
WHERE esb = 'Q'
ORDER BY ARRIVALDATETIME ASC)
SELECT @ESB (SELECT esb FROM INSERTED)
IF @ESB = '1'
BEGIN
UPDATE SOA.dbo.photos_TEST
SET esb = '0'
WHERE id = (SELECT TOP(1) ID
FROM SOA.dbo.photos_TEST
WHERE esb = 'Q'
ORDER BY ARRIVALDATETIME ASC)
END
经过几个小时的谷歌搜索并尝试我还没有找到为什么行没有更新为'0'。我怀疑AFTER UPDATE触发器中的UPDATE是它无法工作的原因。有人提出任何提示或更好的解决方案吗?
干杯,
彼得
答案 0 :(得分:1)
在处理多个更新时,这两种方法都不起作用。
为什么你甚至需要根据具体情况来做。你无论如何都不能在桌子上运行更新。
可能有以下几点:
If Update(ESB)
begin
Update a
Set AnotherColumn = 0
From YourTable a
Join inserted ins on a.Id = ins.Id
Where ins.ESB = 1
end
这将检查它是否是已更新的ESB列。如果是,那么它运行update语句将AnotherColumn
设置为零,其中ESB值为1
我认为这应该对你有用
答案 1 :(得分:0)
感谢Barry的帮助,如果确定了触发器的话;
CREATE TRIGGER TR_PHOTO_AU
ON SOA.dbo.photos
AFTER UPDATE
AS
DECLARE @MAXCONC INT -- Maximum concurrent processes
DECLARE @CONC INT -- Actual concurrent processes
SET @MAXCONC = 1 -- 1 concurrent process
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON
-- If column esb is involved in the update, does not necessarily mean
-- that the column itself is updated
If ( Update(ESB) )
BEGIN
-- If column esb has been changed to 1
IF ((SELECT esb FROM INSERTED) = '1')
BEGIN
-- count the number of (imminent) active processes
SET @CONC = (SELECT COUNT(*)
FROM SOA.dbo.photos pc
WHERE pc.esb in ('0','R'))
-- if maximum has not been reached
IF NOT ( @CONC >= @MAXCONC )
BEGIN
-- set additional rows esb to '0' to match @MAXCONC
UPDATE TOP(@MAXCONC-@CONC) p2
SET p2.esb = '0'
FROM ( SELECT TOP(@MAXCONC-@CONC) p1.esb
FROM SOA.dbo.photos p1
WHERE p1.esb = 'Q'
ORDER BY p1.arrivaldatetime ASC
) p2
END
END
END