SQL Server 修改数据库名的逻辑实现

 有一批数据库:

DBBI   --主要数据库用这个

DBBI_20211231

DBBI_20220101

.....

主要为了实现传一个日期参数进来,把带日期的数据库名变成DBBI,把DBBI变成带日期的DBBI_20211231

USE master; 

go

declare @date nvarchar(20)

set @date='2022-12-31'

 

set @date=REPLACE(@date,'-','')

 

declare @calcDate datetime

SELECT  @calcDate=CALCULATE_DATE FROM [DBBI].[dbo].[V_PROCESS_STATUS]

set @calcDate = DATEADD(DAY, 1, @calcDate)

--select REPLACE(CONVERT(VARCHAR(10), @calcDate, 120),'-','')

 

declare @sql nvarchar(300)

set @sql='ALTER DATABASE DBBI SET SINGLE_USER WITH ROLLBACK IMMEDIATE;'

 

set @sql+='ALTER DATABASE DBBI MODIFY NAME = DBBI_'+REPLACE(CONVERT(VARCHAR(10), @calcDate, 120),'-','')+';'

 

set @sql+='ALTER DATABASE DBBI_'+REPLACE(CONVERT(VARCHAR(10), @calcDate, 120),'-','')+' SET MULTI_USER;'

 

exec(@sql)

 

set @sql='ALTER DATABASE DBBI_'+@date+' SET SINGLE_USER WITH ROLLBACK IMMEDIATE;'

 

set @sql+='ALTER DATABASE DBBI_'+@date+' MODIFY NAME = DBBI;'

 

set @sql+='ALTER DATABASE DBBI SET MULTI_USER;'

 

exec(@sql)

你可能感兴趣的:(C#,数据库,sql,sqlserver)