I am trying to write my 1st of many Stored Procedures which will perform functions on a MS SQL database (source) and a remote linked MS SQL database (target) such as :
The 1st one that I have tried to develop is a stored procedure which will validate that a specific database exists on either Source/Target server.
CREATE OR ALTER PROCEDURE Tios_Check_DB_Exists
(@linkedServer nvarchar(max),
@database nvarchar(max),
@rowCount int OUTPUT,
@sql nvarchar(max)=' ')
AS
BEGIN
SET NOCOUNT ON;
SET @sql='select @rowCount = Count(*) from '+@linkedServer+ '.master.dbo.sysdatabases where lower(name)=lower('''+@database+''')'
Print @sql
exec (@sql)
RETURN @rowCount
END
GO
Calling the stored procedure
BEGIN
DECLARE @rowCount int
exec @rowCount = [XXX\SQLSERVER2019].master.dbo.Tios_Check_DB_Exists '[XXX\SQLSERVER2019]','DTA_TESTDTA' ,-1
print @rowCount
END
Result
select @rowCount = Count(*) from [XXX\SQLSERVER2019].master.dbo.sysdatabases where lower(name)=lower('DTA_TESTDTA')
Msg 137, Level 15, State 1, Line 62
Must declare the scalar variable "@rowCount".
-1
Completion time: 2022-01-01T20:17:52.9290824+00:00
Why are I getting the above error when I have defined @rowCount ?
How can I return any error messages encountered ?