Home How many lines are executed after IF?
Reply: 2

How many lines are executed after IF?

Mr JF
1#
Mr JF Published in 2018-01-12 10:07:48Z

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.

Md. Suman Kabir
2#
Md. Suman Kabir Reply to 2018-01-12 10:35:36Z

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.

i486
3#
i486 Reply to 2018-01-12 10:12:37Z

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

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.312456 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO