在线求助关于SQL数据库修改表结构的语句

[复制链接]
查看11 | 回复6 | 2005-10-30 17:05:33 | 显示全部楼层 |阅读模式
我想用SQL的脚本语句修改表结构.
主要是想先判断一下这个表里是否有这一列,如果没有的话就在这表中插入一列,然后设置一个初始值,如果有就不进行任何操作了.
肯请这里的大师们帮我写个简单的例子.谢谢了


回复

使用道具 举报

千问 | 2005-10-30 17:05:33 | 显示全部楼层
if not exists(select 1 from 数据库名.dbo.syscolumns

where object_name(id)='表名'

and name='列名')
begin
alter table表名
add 新列名 数据类型 null
end
回复

使用道具 举报

千问 | 2005-10-30 17:05:33 | 显示全部楼层
那我该怎么样给这个字段加一个默认值呢?
回复

使用道具 举报

千问 | 2005-10-30 17:05:33 | 显示全部楼层
1、create tabledbo.demo
( [id] int,
[name] char(10) default 'Beijing'
)
2、create default...
sp_bindefault..
回复

使用道具 举报

千问 | 2005-10-30 17:05:33 | 显示全部楼层
我想把这两个语句写在一起,如果能一块执行就好了.
回复

使用道具 举报

千问 | 2005-10-30 17:05:33 | 显示全部楼层
自己顶一下,大家帮帮我啊.还没有搞定哩.
我在调试时写了一条这样的语句.
if not exists (select * from sysobjects a,syscolumns b where a.id=b.id and a.name='student' and b.name='score' )
begin
alter table student add score int(4)
update student set score=123
end
但是调试不能,只能这样
if not exists (select * from sysobjects a,syscolumns b where a.id=b.id and a.name='student' and b.name='score' )
alter table student add score int(4)
update student set score=123
但是这不是我想要的,这样的话,如果原来有这个字段,会把这个字段都替换过去的.
回复

使用道具 举报

千问 | 2005-10-30 17:05:33 | 显示全部楼层
if not exists(select 1 from 数据库名.dbo.syscolumns
where object_name(id)='表名'
and name='列名')
begin
alter table 表名
add 新列名 数据类型DEFAULT constant_expression
end
是不是想要这个?
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题

0

回帖

4882万

积分

论坛元老

Rank: 8Rank: 8

积分
48824836
热门排行