调整SQLServer2000运行中数据库结构

开发过程中的数据库结构结构,不可避免的会需要反复的修改。最麻烦的情况莫过于开发者数据库结构已经修改,而实际应用中数据库又有大量数据,如何在不影响 数据库中数据情况下,更新数据结构呢?当然,我们可以手工对应用数据库表结构各个添加、更正、删除的字段一一调整,这对一两个字段来说,是比较简单的,如 果改动比较大的时候,这个过程将是非常繁琐的。本文意在介绍使用sqlserver2000 t-sql语句进行数据库结构调整,希望能够给各位带来些方便。下面以现有数据库表hr_user为例,讲解如何进行这类操作。

hr_user现有结构:

[userid] [int] not null ,用户id,主键 
[username] [varchar] (50) not null ,用户姓名 

一、数据库添加新字段

现在,需要在hr_user中添加字段用户昵称[nickname] [varchar] (50) 不为空,出生日期[birthday] [datetime] 不为空。
在开发数据库中我们已经添加了这两个字段,在查询分析器或者企业管理器中生成新表的构造语句如下:

if exists (select * from dbo.sysobjects where id = object_id(n'[dbo].[hr_user]') and objectproperty(id, n'isusertable') = 1) 
drop table [dbo].[hr_user] 
go 
create table [dbo].[hr_user] ( 
[userid] [int] not null , 
[username] [varchar] (50) collate chinese_prc_cs_as not null , 
[nickname] [varchar] (50) collate chinese_prc_cs_as not null , 
[birthday] [datetime] not null 
) on [primary] 
go 
alter table [dbo].[hr_user] add 
constraint [df_hr_user_userid] default (0) for [userid], 
constraint [df_hr_user_username] default ('') for [username], 
constraint [df_hr_user_nickname] default ('') for [nickname], 
constraint [df_hr_user_birthday] default (getdate()) for [birthday], 
constraint [pk_hr_user] primary key clustered 
( 
[userid] 
) on [primary] 
go 
exec sp_addextendedproperty n'ms_description', n'出生日期', n'user', n'dbo', n'table', n'hr_user', n'column', n'birthday' 
go 
exec sp_addextendedproperty n'ms_description', n'用户昵称', n'user', n'dbo', n'table', n'hr_user', n'column', n'nickname' 
go 
exec sp_addextendedproperty n'ms_description', n'用户id', n'user', n'dbo', n'table', n'hr_user', n'column', n'userid' 

这时候,我们来构建应用数据库的修改语句,t-sql修改表结构添加新字段语法为alter table tablename add,这样我们要添加两个字段就应该这样写:

alter table [dbo].[hr_user] add
 [nickname] [varchar] (50) collate chinese_prc_cs_as not null default(''),
 [birthday] [datetime] not null default(getdate())
go

 其实中间的语句只是简单的拷贝创建语句中对应两个字段的两句。再加上两句添加描述的语句,就大功告成。

exec sp_addextendedproperty n'ms_description', n'出生日期', n'user', n'dbo', n'table', n'hr_user', n'column', n'birthday'
go
exec sp_addextendedproperty n'ms_description', n'用户昵称', n'user', n'dbo', n'table', n'hr_user', n'column', n'nickname'
go

 二、数据库修改字段
 现在我们发现username、nickname字段长度不够,需要修改为100

alter table [hr_user] alter
 column [username] [varchar] (100) collate chinese_prc_cs_as not null
go

alter table [hr_user] alter
 column [nickname] [varchar] (100) collate chinese_prc_cs_as not null
go

(0)
上一篇 2022年3月21日
下一篇 2022年3月21日

相关推荐