Emel Uras Emel Uras - 5 months ago 12
SQL Question

How to write nested if statements in SQL Server 2008

I have a query in SQL Server 2008 like below:

declare @checkValue int = 1
IF (@checkValue = 1)
(
IF OBJECT_ID('tempdb..#newtable') IS NOT NULL DROP TABLE #newtable
Select Id
into #newtable
From #oldtable
);


This is not working since the second if clause which is inside the main IF clause. How can I fix it and use nested if statements like that?

Any help would be appreciated. Thanks

Answer

Almost, but you need BEGIN and END instead of parenthesis:

declare @checkValue int = 1
IF (@checkValue = 1)
BEGIN
     IF OBJECT_ID('tempdb..#newtable') IS NOT NULL DROP TABLE #newtable
     Select Id
     into #newtable
     From #oldtable
END;