開發過程中的數據庫結構結構,不可避免的會需要反復的修改。最麻煩的情況莫過于開發者數據庫結構已經修改,而實際應用中數據庫又有大量數據,如何在不影響數據庫中數據情況下,更新數據結構呢?當然,我們可以手工對應用數據庫表結構各個添加、更正、刪除的字段一一調整,這對一兩個字段來說,是比較簡單的,如果改動比較大的時候,這個過程將是非常繁瑣的。本文意在介紹使用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'
go
exec sp_addextendedproperty n'ms_description', n'用戶姓名', n'user', n'dbo', n'table', n'hr_user', n'column', n'username'
go
這時候,我們來構建應用數據庫的修改語句,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