Note that there are some explanatory texts on larger screens.

plurals
  1. POSQL Server IF NOT EXISTS Usage?
    primarykey
    data
    text
    <p>Ok, so my schema is this:</p> <p>Table: Timesheet_Hours</p> <p>Columns:</p> <ul> <li>Timesheet_Id (PK, int)</li> <li>Staff_Id (int)</li> <li>BookedHours (int)</li> <li>Posted_Flag (boolean)</li> </ul> <p>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.</p> <p>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.</p> <p>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.</p> <p>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 checkint to see that the record it is going to update already exists. The issue is that it always raises an error.</p> <p>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.</p> <pre><code>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 </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload