更改存储过程中的表
第一次发帖,如果这个问题已经得到解答,请告诉我!我试着四处寻找,但什么也没找到。
在我的存储过程中,我在进行一些修改时选择临时表(我已将其简化为基本问题)。
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
在查询分析器中,如果突出显示 &按顺序分别运行它们,我得到所需的输出。
ColA ColB ColC ColD ColE
---- ---- ----- ----- -----
a b c d e
但是,当我一起运行它们时,出现以下错误:
(1 row(s) affected)
Msg 207, Level 16, State 1, Line 10
Invalid column name 'colC'.
看起来 ALTER TABLE 语句被跳过?我在每个命令后插入了 GO 语句,并且代码在查询分析器中运行。但是,我不知道如何在存储过程中复制它。 (s-procs 有“GO”等价物吗?)
非常感谢任何帮助!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
GO 不是 T-SQL 的一部分,它是许多 SQL Server 工具支持的批处理分隔符。
您通常可以使用 EXEC 执行 ALTER TABLE,但如果您在创建后需要立即进行 ALTER 的问题是如何获取虚拟列,那么您的具体示例可以简单地完成:
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: