1 --获取所有数据库的名称 2 select [name] from master.dbo.sysdatabases where [name]='master' 3 4 --判断数据库是否存在 5 if exists(select [name] from master.dbo.sysdatabases where [name]='master') 6 7 begin 8 select 1; 9 end 10 else 11 begin 12 select 0; 13 end 14 15 --分离数据库-----要先获取所有的数据库 16 if exists(select [name] from master.dbo.sysdatabases where [name]='zuobiao') 17 18 begin 19 exec sp_detach_db 'zuobiao' 20 select 1; 21 end 22 else 23 begin 24 select 0; 25 end 26 27 --附加数据库-------要判断要附加的数据库是否存在 28 if exists(select [name] from master.dbo.sysdatabases where [name]='zuobiao') 29 30 begin 31 select 0; 32 end 33 else 34 begin 35 exec sp_attach_db @dbname='zuobiao' 36 ,@filename1='D:\Program Files\SQL Server\MSSQL.1\MSSQL\Data\zuobiao.mdf' 37 ,@filename2='D:\Program Files\SQL Server\MSSQL.1\MSSQL\Data\zuobiao_log.LDF' 38 select 1; 39 end 40 41 ---备份数据库 42 use master 43 go 44 backup database demo to disk='d:\database\demo.bak' 45 46 --还原数据库 47 use master 48 go 49 restore database demo 50 from disk='d:\database\demo.bak' 51 with replace