在应用软件系统的开发中,对数据库的操作是必不可少的。在开发团队中,一般不允许开发人员随意的修改表结构、视图结构或系统数据,这对项目组来说,危害是致命的,特别是在已经上线的环境中,更是严禁这种行为。
我们采取的一般做法是开发人员提交SQL脚本,统一交由管理员来执行这些脚本,在执行脚本过程中可能会遇到多次执行的情况(比如管理员第一次执行脚本文件时出错,开发人员修改后,再执行该文件,可能其中有些正确的语句已经执行了。),重复执行语句的结果可能造成重复数据、SQL报错等。如何避免这种情况的发生呢,在我们撰写脚本语句时就要先作判断,避免因为某个语句出错而导致整个脚本文件不能执行下去的情况发生。
一般可以使用if exists/if not exists语句进行判断,以下列出一些常用的判断(在SQL Server 2005下)。
1、插入初始数据或配置数据
在作数据初始时,如果插入的数据不加以判断,可能会插入多条相同的配置数据,可能会引起系统的严重错误。在插入数据时可以使用以下语句加以判断:
if not exists(select * from table1 where field1 = value1)
begin
insert table1 (field1,field2 ) values (value1, value2)
end
2、新建表
if not exists (select * from sys.tables where name = 'table2')
begin
create table (...)
end
3、修改列
if not exists (select * from sys.columns, sys.tables
where sys.columns.object_id = sys.tables.object_id
and sys.columns.name ='field3'
and sys.tables.name ='table3')
begin
alter table add field3 varchar(50)
end
else
begin
alter table alter column field3 varchar(50)
-- alter table del column field3
end
4、修改视图、存储过程、同义词等
--视图
if exists (select * from sys.views where name = 'view1')
drop view view1
go
create view view1
...
--存储过程
if exists (select * from sys.objects where name = 'proceduer1')
drop proc procedure1
go
create proc procedure1
...
--同义词
if exists (select * from sys.synonyms where name = 'synonyms1')
drop synonyms synonyms1
go
create synonyms synonyms1
...