问题
I have a temporary table created at the beginning of this stored procedure. It is created successfully and can be selected from and inserted to.
Here is the create statement
CREATE TABLE #tmpImportData (GuideFirstName VARCHAR(MAX), GuideLastName VARCHAR(MAX),
email VARCHAR(MAX), group_id_text VARCHAR(MAX), CandidateName VARCHAR(MAX),
grade_text VARCHAR(5), dateofbirth DATE
)
My problem is trying to update a column after I alter the temporary table. I get the error
Msg 207, Level 16, State 1
invalid column name
Code:
declare @SQl1 nvarchar(max)
set @SQL1 ='
ALTER TABLE #tmpImportData
ADD group_id INT
ALTER TABLE #tmpImportData
ADD guide_id INT
ALTER TABLE #tmpImportData
ADD password_plain_text VARCHAR(500)
ALTER TABLE #tmpImportData
ADD guide_email VARCHAR(500)
ALTER TABLE #tmpImportData
ADD class_id INT'
exec sp_executesql @Sql1
UPDATE #tmpImportData
SET group_id = CAST(group_id_text AS INT)
UPDATE #tmpImportData
SET group_id = 0 WHERE group_id IS NULL
回答1:
try do it like this
declare @SQl1 nvarchar(max)
set @SQL1 ='
ALTER TABLE #tmpImportData
ADD ['+@group_id+'] INT
ALTER TABLE #tmpImportData
ADD ['+@guide_id+'] INT
ALTER TABLE #tmpImportData
ADD ['+@password_plain_text+'] VARCHAR(500)
ALTER TABLE #tmpImportData
ADD ['+@guide_email+'] VARCHAR(500)
ALTER TABLE #tmpImportData
ADD ['+@class_id+]' INT'
exec @Sql1
UPDATE #tmpImportData
SET group_id = CAST(group_id_text AS INT)
UPDATE #tmpImportData
SET group_id = 0 WHERE group_id IS NULL
来源:https://stackoverflow.com/questions/27339995/why-is-my-alter-table-statement-not-properly-adding-a-column-to-my-temporary-tab