更改存储过程中的表

发布于 2024-10-30 19:41:17 字数 768 浏览 2 评论 0原文

第一次发帖,如果这个问题已经得到解答,请告诉我!我试着四处寻找,但什么也没找到。

在我的存储过程中,我在进行一些修改时选择临时表(我已将其简化为基本问题)。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

Bonjour°[大白 2024-11-06 19:41:17

GO 不是 T-SQL 的一部分,它是许多 SQL Server 工具支持的批处理分隔符。

您通常可以使用 EXEC 执行 ALTER TABLE,但如果您在创建后需要立即进行 ALTER 的问题是如何获取虚拟列,那么您的具体示例可以简单地完成:

SELECT 'a' AS ColA
    ,'b' AS ColB
    ,CAST(NULL AS char(5)) AS ColC
    ,CAST(NULL AS char(5)) AS ColD
    ,CAST(NULL AS char(5)) AS ColE
INTO #tmp

UPDATE #tmp
SET ColC = 'c',
    ColD = 'd',
    ColE = 'e'
FROM #tmp

SELECT * FROM #tmp

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:

SELECT 'a' AS ColA
    ,'b' AS ColB
    ,CAST(NULL AS char(5)) AS ColC
    ,CAST(NULL AS char(5)) AS ColD
    ,CAST(NULL AS char(5)) AS ColE
INTO #tmp

UPDATE #tmp
SET ColC = 'c',
    ColD = 'd',
    ColE = 'e'
FROM #tmp

SELECT * FROM #tmp
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文