How many lines are executed after IF?

Consider the part of the SQL script as follows:

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 rows executed? How about the rest of my script further down (not included - creates a table); Is there a way to limit how many lines are executed after an IF ? I can not find the answer to this question, since this is a rather ambiguous search.

+5
source share
2 answers

Do it as 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 do not use the BEGIN and END blocks, only the first sql statement will be processed in accordance with the IF condition, and the last sql statements will be executed each time it is run, and you will get an error if tableName does not exist.

+5
source

Only the first request is executed. For more than 1, you need a BEGIN - END block.

+2
source

Source: https://habr.com/ru/post/1274656/


All Articles