SQL Server IF NOT EXISTS Usage?

前端 未结 1 1572
不知归路
不知归路 2020-12-09 14:29

Ok, so my schema is this:

Table: Timesheet_Hours

Columns:

  • Timesheet_Id (PK, int)
  • Staff_Id (int)
  • BookedHours (int)
  • Poste
相关标签:
1条回答
  • 2020-12-09 15:02

    Have you verified that there is in fact a row where Staff_Id = @PersonID? What you've posted works fine in a test script, assuming the row exists. If you comment out the insert statement, then the error is raised.

    set nocount on
    
    create table Timesheet_Hours (Staff_Id int, BookedHours int, Posted_Flag bit)
    
    insert into Timesheet_Hours (Staff_Id, BookedHours, Posted_Flag) values (1, 5.5, 0)
    
    declare @PersonID int
    set @PersonID = 1
    
    IF EXISTS    
        (
        SELECT 1    
        FROM Timesheet_Hours    
        WHERE Posted_Flag = 1    
            AND Staff_Id = @PersonID    
        )    
        BEGIN
            RAISERROR('Timesheets have already been posted!', 16, 1)
            ROLLBACK TRAN
        END
    ELSE
        IF NOT EXISTS
            (
            SELECT 1
            FROM Timesheet_Hours
            WHERE Staff_Id = @PersonID
            )
            BEGIN
                RAISERROR('Default list has not been loaded!', 16, 1)
                ROLLBACK TRAN
            END
        ELSE
            print 'No problems here'
    
    drop table Timesheet_Hours
    
    0 讨论(0)
提交回复
热议问题