1

I have a code that looks something like this

declare @query = '
   Alter Table Temp
   Add NewColumn int

   update Temp
   set NewColumn = 100'

exec (@query)

It will give error NewColumn does not exist. But if I run this normally without using @query = '' it runs fine. Also, what is it called when you run the code like this with the @query = ' text ' then exec?

0

1 Answer 1

3

You are executing them as one batch in dynamic SQL. So the compiler will not allow it, because at compilation time the column does not exist yet.

It is not true that it would work when executed together. you are executing them line-by-line in separate batches.

   Alter Table Temp
   Add NewColumn int
   update Temp
   set NewColumn = 100
   Alter Table Temp
   Add NewColumn int

   update Temp
   set NewColumn = 100

So you need to do this

declare @query nvarchar(max) = '
   Alter Table Temp
   Add NewColumn int
';

exec sp_executesql @query;

set @query = '
   update Temp
   set NewColumn = 100
';

exec sp_executesql @query;

db<>fiddle

The ALTER could also go outside the dynamic SQL as well.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.