IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FN_BASIT_ID_SIFRELE]') AND xtype in (N'FN', N'IF', N'TF'))
DROP FUNCTION [dbo].FN_BASIT_ID_SIFRELE
GO

CREATE FUNCTION [dbo].[FN_BASIT_ID_SIFRELE] (@id AS INTEGER)  
RETURNS NVARCHAR(30) AS  
BEGIN 	
	IF @id IS NULL RETURN ''

	DECLARE @STRID NVARCHAR(20) = CONVERT(NVARCHAR,@id)
	DECLARE @STRIDSIFRELI NVARCHAR(30) = ''
	DECLARE @SAY INT = 0


	SET @STRIDSIFRELI =	CHAR(120-CONVERT(INT,SUBSTRING(@STRID,1,1))) + 
						CHAR(107+CONVERT(INT,SUBSTRING(@STRID,1,1))) + 
						CONVERT(VARCHAR,50-CONVERT(INT,SUBSTRING(@STRID,1,1))) +
						CHAR(110-CONVERT(INT,SUBSTRING(@STRID,1,1)))
	SET @SAY=2
	WHILE @SAY <= LEN(@STRID)
	BEGIN
		SET @STRIDSIFRELI = @STRIDSIFRELI + CHAR(100+CONVERT(INT,SUBSTRING(@STRID,@SAY,1)))
		SET @SAY = @SAY + 1;
	END

	SET @STRIDSIFRELI = @STRIDSIFRELI + CONVERT(VARCHAR,9-CONVERT(INT,SUBSTRING(@STRID,LEN(@STRID),1)))+
										CHAR(115-CONVERT(INT,SUBSTRING(@STRID,LEN(@STRID),1)))

	RETURN @STRIDSIFRELI
END
GO

IF EXISTS (SELECT [name] FROM [sys].[database_principals] WHERE [type] = N'S' AND [name] = N'mediwebuser')
BEGIN
	BEGIN TRY
		GRANT EXECUTE ON [dbo].[FN_BASIT_ID_SIFRELE] TO [mediwebuser]
	END TRY
	BEGIN CATCH
	END CATCH
END
GO
