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.
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.
Only first query is executed. For more than 1 you need BEGIN
- END
block.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With