Technical Article

Synchronize a function between two servers

,

This script is the same method with spSynchStoredProcedure but used for views.

To run this stored procedure, you need to create two linked servers for your source server and your target server. You can create them in local SQL Server and then run this to synchronize.

For example, your development server is called DEV and your production server is called PROD, and you create two linked servers in local SQL Server with the same name. Assumed that your database between DEV and PROD have the same name: TestDB.

This procedure may be useful if your function is not over 4000 characters. If it's over 4000 characters, you have to modify it a little.

If you want to synchronize a function called TestFunc between TestDB of DEV and PROD, you can excute like that:

EXEC dbo.spSynchFunction @FunctionName = 'TestFunc', @SourceServer = 'DEV', @SourceDatabase = 'TestDB', @TargetServer = 'PROD', @TargetDatabase = 'TestDB'

 

CREATE PROCEDURE [dbo].[spSynchFunction]
@FunctionName VARCHAR(50) = NULL,
@SourceServer VARCHAR(50) = NULL,
@SourceDatabase VARCHAR(50) = NULL,
@TargetServer VARCHAR(50) = NULL,
@TargetDatabase VARCHAR(50) = NULL
AS
BEGIN
SET NOCOUNT ON;
DECLARE @STRSQL NVARCHAR(MAX);
DECLARE @Params NVARCHAR(MAX);
DECLARE @IsExisted BIT;
DECLARE @Source NVARCHAR(MAX);
SET @IsExisted = 0;
SET @STRSQL = N' SELECT @IsExisted = 1
FROM ' + @TargetServer + '.' + @TargetDatabase + '.sys.objects
WHERE name = ''' + @FunctionName + ''' AND Type IN (''FN'', ''TF'',''IF'')';
SET @Params = N'@IsExisted BIT OUTPUT';
EXEC sp_executesql @STRSQL, @Params, @IsExisted = @IsExisted OUTPUT
IF (@IsExisted = 1)
BEGIN
SET @STRSQL = N'EXEC ' + @TargetServer + '.' + @TargetDatabase + 'dbo.sp_executesql N''DROP FUNCTION ' + @FunctionName + '''';
EXECUTE(@STRSQL);
END;

SET @STRSQL = N'SELECT @Source = t1.text 
FROM ' + @SourceServer + '.' + @SourceDatabase + '.dbo.syscomments t1
INNER JOIN ' + @SourceServer + '.' + @SourceDatabase + '.dbo.sysobjects t2 on t1.id = t2.id
WHERE t2.xtype IN (''FN'', ''TF'',''IF'')
AND t2.name = ''' + @FunctionName + '''';
SET @Params = N'@Source NVARCHAR(MAX) OUTPUT'
EXEC sp_executesql @STRSQL, @Params, @Source = @Source OUTPUT

SET @Source = REPLACE(@Source, '''', '''''');
SET @STRSQL = N'EXEC ' + @TargetServer + '.' + @TargetDatabase + '.dbo.sp_executesql N''' + @Source + '''';
--PRINT @ViewSource;
--PRINT @STRSQL;
EXECUTE(@STRSQL);
END

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating