在一个存储过程中多次插入和选择

时间:2010-10-16 12:06:12

标签: sql sql-server tsql stored-procedures

我想创建一个

的程序

A)检查TicketNumberInput是否在表Tix_number.TicketNumber中。

B)如果确实存在,请更新记录以将UID设置为@uid并将Claimdate设置为GetDate()

AND ...

C)将记录插入另一个表(交易记录表)

如果记录确实存在,只需将记录添加到事务日志中,STATUS = 2(失败)。

这是我的代码到目前为止,但它似乎没有问题检查IF语句和更新记录和插入另一条记录。如何在语句中添加许多检查。开始结束似乎不起作用

create procedure [dbo].[UpdateTicketNumber]
@TicketNumberInput uniqueidentifier, 
@UID   int
as 
IF EXISTS(
BEGIN
    SELECT *
    FROM [tixtowin].[dbo].[Tix_Number]
    where @TicketNumberInput = Tix_Number.TicketNumber)
    PRINT 'CORRECT RECORD'

    Update Tix_Number 
    Set Tix_Number.UID = @uid, ClaimDate = GETDATE()
    where TicketNumber = @TicketNumberInput

    /* Success - insert transaction message. Status = 1 */
    INSERT INTO [Tix_Transaction]
    ([Tix_Number],[UID], [status], [Datetime])
    VALUES
    (@TicketNumberInput, @UID, '1', GetDate())

    End
    ELSE

    /* Failed - insert transaction message. Status = 2 */
    INSERT INTO [Tix_Transaction]
    ([Tix_Number],[UID], [status], [Datetime])
    VALUES
    (@TicketNumberInput, @UID, '2', GetDate())

    PRINT 'INCORRECT RECORD'

谢谢你的帮助!!!

1 个答案:

答案 0 :(得分:4)

您的IF没有测试。你需要测试,然后做一些事情:

create procedure [dbo].[UpdateTicketNumber] 
@TicketNumberInput uniqueidentifier,  
@UID   int 

as  
IF EXISTS (SELECT NULL
    FROM [tixtowin].[dbo].[Tix_Number] 
    where @TicketNumberInput = Tix_Number.TicketNumber) 
BEGIN 

    PRINT 'CORRECT RECORD' 

    Update Tix_Number  
    Set Tix_Number.UID = @uid, ClaimDate = GETDATE() 
    where TicketNumber = @TicketNumberInput 

    /* Success - insert transaction message. Status = 1 */ 
    INSERT INTO [Tix_Transaction] 
    ([Tix_Number],[UID], [status], [Datetime]) 
    VALUES 
    (@TicketNumberInput, @UID, '1', GetDate()) 

END 
ELSE 
BEGIN 
    /* Failed - insert transaction message. Status = 2 */ 
    INSERT INTO [Tix_Transaction] 
    ([Tix_Number],[UID], [status], [Datetime]) 
    VALUES 
    (@TicketNumberInput, @UID, '2', GetDate()) 

    PRINT 'INCORRECT RECORD' 
END