根据另一个表中的条件更新表

时间:2012-08-14 13:44:54

标签: sql sql-server-2008

我有一张桌子ATMStatusHistory。我想要一个IF条件,该条件规定如果特定故障单的所有Resolved列值都为1,则将Ticket表更新为Closed = 1,以获取与此相关的所有代码票。

Code    RawFeed   Resolved  Ticket
2341283 2350426   0         205656
2341460 2350603   1         205656
2341597 2350740   1         205656
2341689 2350832   1         205656
2341825 2350968   0         205656

我写了一个IF条件,但它不起作用:

    If Not Exists (Select * From ATMStatusHistory Where Ticket = @OriginalTicket
         AND Resolved=0 And RawFeed = 0)
        {
Insert InTo TicketFollowUp(Ticket, FollowUpText, FollowUpBy, FollowUpOn) 
  Select Code, Comments, UpdatedBy, UpdatedOn 
  From Ticket Where Code = @OriginalTicket                  

          Update Ticket Set Closed=1, ClosedOn=GetDate(), UpdatedBy=0, 
           UpdatedOn=GetDate(), Comments=' Ticket Closed by System as all Faults cleared. ' 
           Where Code = @OriginalTicket         
        }   

2 个答案:

答案 0 :(得分:3)

添加insert语句的新要求:

IF NOT EXISTS 
(
  SELECT 1 FROM dbo.ATMStatusHistory 
    WHERE Ticket = @OriginalTicket
    AND Resolved = 0 AND RawFeed = 0
)
AND EXISTS
(
  -- want to be sure we only "close" a ticket once
  SELECT 1 FROM dbo.Ticket
    WHERE Ticket = @OriginalTicket
    AND Closed = 0
)
BEGIN
  INSERT dbo.TicketFollowUp(Ticket, FollowUpText, FollowUpBy, FollowUpOn) 
    SELECT Code, Comments, UpdatedBy, UpdatedOn
    FROM dbo.Ticket WHERE Code = @OriginalTicket;

  UPDATE dbo.Ticket
   SET Closed   = 1, 
      ClosedOn  = GETDATE(), 
      UpdatedBy = 0, 
      UpdatedOn = GETDATE(),
      Comments  = ' Ticket Closed by System as all Faults cleared. ' 
  WHERE Code = @OriginalTicket;
END

答案 1 :(得分:1)

你可以尝试这个演示:

CREATE TABLE #ATMStatusHistory  (Code  INT,  RawFeed  
    INT, Resolved INT, Ticket INT)
INSERT #ATMStatusHistory VALUES
(2341283 ,2350426   ,0         ,205656),
(2341460 ,2350603   ,1         ,205656),
(2341597 ,2350740   ,1         ,205656),
(2341689 ,2350832   ,1         ,205656),
(2341825 ,2350968   ,0         ,205656)

CREATE TABLE #Ticket (Code INT, Closed INT, ClosedOn 
    DATETIME, UpdatedBy INT, UpdatedOn DATETIME, 
    Comments VARCHAR(1000))
INSERT #Ticket VALUES
(2341283 ,1, '20120101', 1, '20120101', 'test'),
(2341460 ,1, '20120101', 1, '20120101', 'test'),
(2341597 ,1, '20120101', 1, '20120101', 'test'),
(2341689 ,1, '20120101', 1, '20120101', 'test'),
(2341825 ,1, '20120101', 1, '20120101', 'test')

DECLARE @OriginalTicket INT = 205656



UPDATE  #Ticket
SET     Closed = 1,
        ClosedOn = GETDATE(), 
        UpdatedBy = 0,
        UpdatedOn = GETDATE(),
        Comments = 'Ticket Closed by System as all Faults cleared.'
FROM    #Ticket a
JOIN    #ATMStatusHistory b ON
        b.Code = a.Code
        AND 1 = ALL(
            SELECT  x.Resolved 
            FROM    #ATMStatusHistory x 
            WHERE   x.Ticket = @OriginalTicket
            AND     x.RawFeed <> 0      
        )

SELECT  *
FROM    #Ticket

DROP TABLE #ATMStatusHistory
DROP TABLE #Ticket