如何判断数据库是否存在

该篇文章为转载,只为参考。

转载连接:http://blog.csdn.net/winlinking/archive/2008/02/20/2109332.aspx

 内容:

if exists(select * from master.dbo.sysdatabases where name = 'SkyBusiness')
begin
drop database SkyBusiness
print 'SkyBusiness 已经存在,已被删除'
end
else
begin
create database SkyBusiness
on primary
(
  name=SkyBusiness_mdf,
  filename='c:\SkyBusiness.mdf',
  size=10mb,
  maxsize=50mb,
  filegrowth=25%
)
log on
(
  name=SkyBusiness_ldf,
  filename='c:\SkyBusiness.ldf',
  size=10mb,
  maxsize=50mb,
  filegrowth=25%
)
print 'SkyBusiness数据库创建成功'
end
--建聚集索引
create clustered index index_yexinwinners
on tablename(column_name)
with fillfactor = 10
--建非聚集索引
create nonclustered index index_yexinwinners
on tablename(column_name)
with fillfactor = 10
--建视图
create view view_name
as
select * from pubs.titles(sql语句,任意)
--建检查视图
create view view_name
as
select * from pubs.titles(sql语句,任意)
with check option
--建加密视图
create view view_name
with encryption
as
select * from pubs.titles(sql语句,任意)

--建表

create table tablename
( ---(字段名,字段类型 自己任意)
stuID int not null identity(1,1) primary key,
stuName varchar(30) not null,
stuAge char(3) not null
)
--添加check约束
alter table tablename
add check(stuAge >0 and stuAge <100)
--添加外键
alter table tablename
add foreign key (stuName)
references Xtablename(stuName)
--添加唯一约束
alter table tablename
add unique(stuID)
---建事务
begin tranaction
update Xtable set Money = Money + 10000 where ID = 1
update Xtable set Money = Money - 10000 where ID = 3
if(@@error <> 0)
begin
print '转帐失败'
rollback transaction
end
else
begin
print '转帐成功'
commit transaction
end

--建游标
declare cursor_name Cursor
for select * from northwind.product
--建更新游标
declare cursor_name Cursor
for select * from northwind.product
for update
--建随意移动游标
declare cursor_name Cursor scroll
for select * from northwind.product
--使用游标
open cursor_name
--关闭游标
close cursor_name
--删除游标
deallocate cursor_name
--移动游标
fetch next -- 下一条记录
fetch last --最后一条记录
fetch first --第一条记录
fetch prior --上一条记录
fetch ABSOLUTE n -- 绝对位置  


另外:在搜索中发现了些方法很实用,记录如下:

判断数据库存在:

if exists(select * from master.dbo.sysdatabases where name = 'SkyBusiness')

或者

if db_id('数据库名称') is not null


如果是判断表是否存在,实用如下格式:

if exists(select * from master.dbo.sysobjects where name = 'SkyBusiness')

或者

if object_id('表名称') is not null

原文地址:https://www.cnblogs.com/xFight/p/1650663.html