Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many lines are executed after IF?

Consider a part of a SQL script like this:

IF OBJECT_ID('dbo.tableName', 'U') IS NOT NULL
ALTER TABLE [dbo].[tableName]
DROP CONSTRAINT PK_tableName
DROP TABLE dbo.tableName

If tableName exists, are all three lines executed? What about the rest of my script further down (not included - it creates the table); Is there a way to limit how many lines get executed after the IF statement? I can't find an answer on this as it's quite an ambiguous search.

like image 946
Syntax Error Avatar asked Jan 12 '18 10:01

Syntax Error


2 Answers

Do it like below :

IF OBJECT_ID('dbo.tableName', 'U') IS NOT NULL
    BEGIN
        ALTER TABLE [dbo].[tableName]
        DROP CONSTRAINT PK_tableName;
        DROP TABLE dbo.tableName;
    END

If you don't use BEGIN and END block, only the first sql statement would be treated under the IF condition and the last sql statements would execute every time you run it and you will get error if tableName does not exist.

like image 140
Md. Suman Kabir Avatar answered Sep 19 '22 18:09

Md. Suman Kabir


Only first query is executed. For more than 1 you need BEGIN - END block.

like image 26
i486 Avatar answered Sep 18 '22 18:09

i486