transactions - What's wrong with this tsql? -


when executing following script, error:

msg 207, level 16, state 1, line 15 invalid column name 'b'.

anyone can explain please? thanks.

drop table ttt; create table ttt(a nvarchar)  if not exists ( select  *                    sys.columns                   object_id = object_id('dbo.ttt')                         , name = 'b' )     , exists ( select *                    sys.columns                   object_id = object_id('dbo.ttt')                         , name = 'a' )      begin          alter table [dbo].ttt add b nvarchar          update  [dbo].ttt         set     b =          alter table [dbo].ttt drop column     end 

it's trying compile of these statements before executes 1st:

 alter table [dbo].ttt add b nvarchar      update  [dbo].ttt     set     b =      alter table [dbo].ttt drop column 

(in fact, tries compile entire batch, not these statements, point still stands - @ point it's trying compile update, column not exist)

when it's trying compile update statement, consults table metadata , correctly finds column doesn't exist.

try execing update statement.

    exec('update  [dbo].ttt     set     b = a'); 

and also, oded says wanting specify size column (otherwise, defaults pointless datatype ever - nvarchar(1))


this script runs without errors:

create table ttt(a nvarchar)  if not exists ( select  *                    sys.columns                   object_id = object_id('dbo.ttt')                         , name = 'b' )     , exists ( select *                    sys.columns                   object_id = object_id('dbo.ttt')                         , name = 'a' )      begin          alter table [dbo].ttt add b nvarchar          exec('update  [dbo].ttt         set     b = a');          alter table [dbo].ttt drop column     end 

Comments

Popular posts from this blog

c# - How to set Z index when using WPF DrawingContext? -

razor - Is this a bug in WebMatrix PageData? -

visual c++ - Using relative values in array sorting ( asm ) -