First time posting, please let me know if this question has already been answered! I tried searching around, but couldn’t find anything.
In my stored procedure, I select into a temp table while I do some modifying (Ive dumbed it down to the basic issue).
SELECT 'a' AS ColA, 'b' AS ColB INTO #tmp
ALTER TABLE #tmp
ADD ColC char(5) NULL,
ColD char(5) NULL,
ColE char(5) NULL
UPDATE #tmp
SET ColC = 'c',
ColD = 'd',
ColE = 'e'
FROM #tmp
SELECT * FROM #tmp
In Query Analyzer, If you highlight & run them separately, in order, I get the desired output.
ColA ColB ColC ColD ColE
---- ---- ----- ----- -----
a b c d e
However, when I run them all together, I get the following error:
(1 row(s) affected)
Msg 207, Level 16, State 1, Line 10
Invalid column name 'colC'.
It looks like the ALTER TABLE statement is being skipped over? I inserted GO statements after each command, and the code worked in query analyzer. However, I cannot figure out how to replicate this in a stored procedure. (Is there a “GO” equivalent for s-procs?)
Any help is greatly appreciated!
GO is not part of T-SQL, it’s a batch separator supported by a number of SQL Server tools.
You can generally do the ALTER TABLE with an EXEC, but if your problem requiring an ALTER immediately after a create was how to get dummy columns, then your specific example can simply be done: