Statement Execution order in SQL Server SQL Script -


i having trouble sql script seems related execution order of statements or possibly error checking sql server prior starting.

this simplification of code background, table finaltable cleared , repopulated script. exists in db not have new columns being added. reference in example, pretend col1 existing column , col2 new.

if run code together, message saying invalid column name 'col2'. if run each block individually, works fine.

block a:

sql create temporary tables 

block b:

drop table dbo.finaltable; create table dbo.finaltable (col1 int, col2 int); 

block c:

insert dbo.finaltable(col1, col2) select col1, col2 #temptable; 

the script snippets posted not detailed enough pinpoint exact cause of error symptoms suggest deferred name resolution. issue not statement execution order compilation order.

sql server checks syntax errors when batch of statements submitted execution. if syntactically correct, statements referencing existing objects validated against existing schema. compilation of statements referencing non-existing objects deferred until execution time. deferred name resolution allows 1 create table , use in same batch:

create table dbo.finaltable (col1 int); --compilation of statement not done until execution time due deferred name resolution select col1 dbo.finaltable; go 

compilation of entire batch fail when statement references non-existing column of existing table. no statements, including first select alter table, executed in batch because col2 not exist when batch compiled:

select col1 dbo.finaltable; alter table dbo.finaltable      add col2 int null; select col1, col2 dbo.finaltable; go 

Comments

Popular posts from this blog

c# - Update a combobox from a presenter (MVP) -

How to understand 2 main() functions after using uftrace to profile the C++ program? -

How to put a lock and transaction on table using spring 4 or above using jdbcTemplate and annotations like @Transactional? -