Search code examples
sql-serversql-server-2008bitwise-operatorstemp-tables

Short circuit in IF clause


I have searched and found nothing about it (I believe it is impossible to do it). My problem is that I have to check if a temporary table exists and also if there is some specific data on that temporary table.

Did anyone faced this before? How did you managed to solve it? I would like to avoid creating milions of IF..ELSE blocks.

EDIT:

IF (OBJECT_ID('tempdb..#tempTable') IS NOT NULL 
AND EXISTS (SELECT * FROM #tempTable WHERE THIS_COLUMN = 'value'))
BEGIN
   PRINT 'Temp table and data exists'
END
ELSE
BEGIN
   PRINT 'Temp table or data does not exist'
END

This is what I want to do. The problem comes when the tempTable doesn't exist (that could happen). It throws an error because, although the first stamement returns false, it continues to execute the second statement. And the SELECT statement is not able to find the table and therefore throws the error. The solution I found was to do this:

IF OBJECT_ID('#tempTable') IS NOT NULL
BEGIN
    IF EXISTS (SELECT * FROM #tempTable WHERE THIS_COLUMN = 'value'
    BEGIN
        PRINT 'Temp table and data exists'
    END
    ELSE
    BEGIN
        PRINT 'Temp table exists but data does not exist'
    END
END
ELSE
BEGIN
    PRINT 'Temp table does not exist'
END

My question would be, is there a way of having 2 conditions and if the first condition returns false not check the second one? Kind of using && in a programming language.


Solution

  • What you are trying to do is not possible as this is a compile time failure and the whole statement needs to be compiled together.

    It won't evaluate the first part of the statement then compile the second part only if that is true. You need to split the test for existence and the query referencing the table into two separate statements so they are compiled separately.