在 if 语句中编写 alter table 查询

发布于 2024-10-15 07:53:48 字数 844 浏览 7 评论 0原文

我有一个表 Person,其中有一列 Status。我尝试执行的 sqlt 文件中存在以下代码

if not exists(select 1 from sysobjects, syscolumns where sysobjects.id = syscolumns.id and sysobjects.name = 'Person' and  syscolumns.name = 'Status')

begin

    print "Inside the if statement" 

end


go

这工作正常,并且不会打印任何内容,因为表和列都存在。 如果我将文件更改为以下内容,

if not exists(select 1 from sysobjects, syscolumns where sysobjects.id = syscolumns.id and sysobjects.name = 'Person' and  syscolumns.name = 'Status')
begin
    print "Inside the if statement"
    alter table Person
    add Status char(5) DEFAULT 'INVLD' NOT NULL
end

go

这不起作用,并且收到以下错误消息:

Msg 2705,Level 16,State 3

Server 'NEXUS',Line 6

每个表中的列名必须是唯一的。表中的列名称“状态” 'Person' 被指定了多次。

为什么在这段代码中它会进入 if 内部?对此有什么解决办法吗?

I have a table Person which has a column Status. Following code exists in the sqlt file which i am trying to execute

if not exists(select 1 from sysobjects, syscolumns where sysobjects.id = syscolumns.id and sysobjects.name = 'Person' and  syscolumns.name = 'Status')

begin

    print "Inside the if statement" 

end


go

This works fine and nothing is printed as the table and the column both exist.
If i change the file to following

if not exists(select 1 from sysobjects, syscolumns where sysobjects.id = syscolumns.id and sysobjects.name = 'Person' and  syscolumns.name = 'Status')
begin
    print "Inside the if statement"
    alter table Person
    add Status char(5) DEFAULT 'INVLD' NOT NULL
end

go

This does not work and i get following error message:

Msg 2705, Level 16, State 3

Server 'NEXUS', Line 6

Column names in each table must be unique. Column name 'Status' in table
'Person' is specified more than once.

Why does it go inside if in this code? What is the solution for this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

少钕鈤記 2024-10-22 07:53:48

我知道您不是在寻找这个答案,但这里是:不要这样做。

原因是,结构变化是总体升级的一部分。对于给定的项目,升级会发生多次(就像一直发生一样),并且通常涉及多个表中的多个列。因此,您制作(或使用)一个工具,仅修改您的结构并独立于使用特定列的业务逻辑来处理该问题。

I know you are not looking for this answer, but here goes: Don't do that.

Reason is, a structure change is part of a general upgrade. For a given project upgrades happen more than once (like all the time), and usually involve more than one column in more than one table. Therefore, you make (or use) a tool that just modifies your structure and handle that problem separately from the business logic that is making use of a particular column.

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