Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using IF / ELSE to determine a SELECT INTO statement

I'm having some strange issues using IF / ELSE to determine which one or two SELECT statements to execute. The error message I'm getting when running the full statement is that my temporary table already exists, but that does not occur if I run two separate executions of two separate IF statements.

Here is the code in SQL Server:

IF (select BusinessDayCount from Calendartbl) <= 1
  BEGIN
    SELECT * into #temp1
    FROM PreviousMonthTbl
  END
ELSE
  BEGIN
    SELECT * into #temp1
    FROM CurrentMonthTbl
  END
like image 791
user2367409 Avatar asked May 09 '13 18:05

user2367409


People also ask

Can we use SELECT statement in IF condition?

It is like a Shorthand form of CASE statement. We can conveniently use it when we need to decide between two options. There are three parts in IIF statement, first is a condition, second is a value if the condition is true and the last part is a value if the condition is false.

How use SELECT statement inside if condition in SQL?

From what I can tell, the select statement should find the number of rows with a value between 2 and 20 and if there are more than 18 rows, the EXISTS function should return 1 and the query will execute the code within the IF statement.

How do you write an IF THEN statement in SQL?

Syntax. IF (a <= 20) THEN c:= c+1; END IF; If the Boolean expression condition evaluates to true, then the block of code inside the if statement will be executed. If the Boolean expression evaluates to false, then the first set of code after the end of the if statement (after the closing end if) will be executed.


1 Answers

It's a "feature" of the syntax checking in SQL Server. You simply cannot "create" a #temporary table twice within the same batch.

This is the pattern you need.

SELECT * into #temp1
FROM PreviousMonthTbl
WHERE 1=0;

IF (select BusinessDayCount from Calendartbl) <= 1
  BEGIN
    INSERT into #temp1 SELECT *
    FROM PreviousMonthTbl
  END
ELSE
  BEGIN
    INSERT into #temp1 SELECT *
    FROM CurrentMonthTbl
  END

If you prefer, you can also express the branch (in this case) as a WHERE clause:

SELECT * into #temp1
FROM PreviousMonthTbl
WHERE (select BusinessDayCount from Calendartbl) <= 1
UNION ALL
SELECT *
FROM CurrentMonthTbl
WHERE isnull((select BusinessDayCount from Calendartbl),2) > 1
like image 161
RichardTheKiwi Avatar answered Oct 08 '22 14:10

RichardTheKiwi