[sql] SQL Server IF NOT EXISTS Usage?

Ok, so my schema is this:

Table: Timesheet_Hours

Columns:

  • Timesheet_Id (PK, int)
  • Staff_Id (int)
  • BookedHours (int)
  • Posted_Flag (boolean)

This is an extremely simplified version of the table, but it will serve for the purposes of this explaination. Assume that a person can only ever have one timesheet record.

What I'm trying to do is add records to another table, called WorkLog. Each record here has a time associated with it. When that table is updated, I want to update Timesheet_Hours as well.

Before I update Timesheet_Hours, I want to check first that the relevant Timesheets haven't already been posted, and then I want to check if there is in fact a record to update in the first place.

The first part of the if statement, which checks to see that the timesheets haven't already been posted, works fine. The problem is the second part. It is checking to see that the record it is going to update already exists. The issue is that it always raises an error.

NB: The code below is extracted from a stored procedure run by the update, insert and delete triggers on the WorkLog table. @PersonID is one of the parameters to that table. The stored procedure works fine if I comment out the second part of this statement.

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

This question is related to sql sql-server stored-procedures

The answer is


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

Examples related to sql

Passing multiple values for same variable in stored procedure SQL permissions for roles Generic XSLT Search and Replace template Access And/Or exclusions Pyspark: Filter dataframe based on multiple conditions Subtracting 1 day from a timestamp date PYODBC--Data source name not found and no default driver specified select rows in sql with latest date for each ID repeated multiple times ALTER TABLE DROP COLUMN failed because one or more objects access this column Create Local SQL Server database

Examples related to sql-server

Passing multiple values for same variable in stored procedure SQL permissions for roles Count the Number of Tables in a SQL Server Database Visual Studio 2017 does not have Business Intelligence Integration Services/Projects ALTER TABLE DROP COLUMN failed because one or more objects access this column Create Local SQL Server database How to create temp table using Create statement in SQL Server? SQL Query Where Date = Today Minus 7 Days How do I pass a list as a parameter in a stored procedure? SQL Server date format yyyymmdd

Examples related to stored-procedures

How to create temp table using Create statement in SQL Server? How do I pass a list as a parameter in a stored procedure? SQL Server IF EXISTS THEN 1 ELSE 2 Stored procedure with default parameters Could not find server 'server name' in sys.servers. SQL Server 2014 How to kill all active and inactive oracle sessions for user EXEC sp_executesql with multiple parameters MySQL stored procedure return value SQL Server: use CASE with LIKE SQL server stored procedure return a table