SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[adminAddServer]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[adminAddServer]
GO


create procedure dbo.adminAddServer
	@pServerName varchar(60),
	@pWorkingFolderRoot varchar(100) 
as
/*************************************************************************
Add the specified server to the SQL Server metadatabase.
Note that this procedure does not create the server and instance working 
folders in the file syatem or SourceSafe sub-projects. This procedure is
intended for use from the Query Analyzer only, thus default parameter
values are used to add the local server entry. Just be aware how dangerous 
it might be 
**************************************************************************/
declare @err int,
	@procedureName varchar(100),
	@serverName varchar(30),
	@instanceName varchar(30)

set @procedureName = db_name() + '.' 
		+ user_name(objectproperty(@@procid,'OwnerId')) 
		+ '.' + object_name(@@procid)

if substring(@pWorkingFolderRoot, datalength(@pWorkingFolderRoot),1) <> '\'
	set @pWorkingFolderRoot = @pWorkingFolderRoot + '\'

if @pServerName is null
	set @pServerName = @@servername

set @instanceName = substring(@pServerName, 
		charindex('\',@pServerName) + 1, 
                datalength(@pServerName))

set @serverName = reverse(substring(reverse(@pServerName), 
		charindex('\',reverse(@pServerName)) + 1, 
		datalength(reverse(@pServerName))))

-- refresh server pool
if (select 2 from Admin.dbo.SqlServer
		where serverName = @serverName
		and instanceName = @instanceName) + 2 = 4
	update Admin.dbo.SqlServer
	set workingFolderRoot = @pWorkingFolderRoot 
	where serverName = @serverName
	and instanceName = @instanceName
else 
	insert Admin.dbo.SqlServer 
		(serverName, 
		instanceName,         
        	workingFolderRoot)
	select @serverName,
		@instanceName,
		@pWorkingFolderRoot

set @err = @@error
if @err <> 0
	goto ErrorHandler

-- audit 
insert Admin.dbo.ActivityLog (activity)
select @procedureName + ' ' + @serverName + '\' + @instanceName 
	+ ', ' + @pWorkingFolderRoot + ' complete successfully'

return

ErrorHandler:
insert Admin.dbo.ActivityLog (activity)
select @procedureName + ' ' + @serverName + '\' + @instanceName 
	+ ', ' + @pWorkingFolderRoot + ' failed with err: ' 
	+ cast(@err as varchar(11)) 
raiserror(59001,16,1,@procedureName)

return -1


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

