use master
go

DROP PROCEDURE SP_RENAME_DB
GO
CREATE PROCEDURE SP_RENAME_DB
@OLD_NAME varchar(32),
@NEW_NAME varchar(32)
as
begin
DECLARE @errno   int
DECLARE @errmsg  varchar(255)
	if not exists (SELECT * FROM sysdatabases WHERE name = @OLD_NAME)
	begin
		select @errno  = 90001,
			   @errmsg = 'Database ' +  @OLD_NAME + ' does not exist. Exiting without action...'
		goto error
	end
	if exists (SELECT * FROM sysprocesses sp INNER JOIN sysdatabases sd ON sp.dbid = sd.dbid and sd.name = @OLD_NAME)
	begin
		select @errno  = 90002,
			   @errmsg = 'There are users connected to database ' +  @OLD_NAME + '. Disconnect all users in order to proceed with renaming. Exiting without action...'
		goto error
	end
	
	
		exec sp_dboption @OLD_NAME, single, true   
		exec sp_renamedb @OLD_NAME , @NEW_NAME
		exec sp_dboption @NEW_NAME, single, false 
	return
error:
	raiserror @errno @errmsg	
end
go