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

CREATE FUNCTION [dbo].[FN_BASIT_ID_SIFRE_AC] (@sifreliid AS NVARCHAR(30))  
RETURNS INT AS  
BEGIN 	
	IF ISNULL(@sifreliid,'')='' RETURN 0
	IF LEN(ISNULL(@sifreliid,''))<5 RETURN 0

	DECLARE @ID INT = 0
	DECLARE @STRID NVARCHAR(30) = ''
	DECLARE @SAY INT = 0

	
	SET @STRID= CONVERT(VARCHAR,ASCII(SUBSTRING(@sifreliid,2,1))-107)

	SET @SAY=6
	WHILE @SAY <= (LEN(@sifreliid)-2)
	BEGIN
		SET @STRID = @STRID + CONVERT(VARCHAR,ASCII(SUBSTRING(@sifreliid,@SAY,1))-100)
		SET @SAY = @SAY + 1;
	END
	
	IF IsNumeric(@STRID)=1
		SET @ID = CONVERT(INT,@STRID)
	ELSE
		SET @ID = 0

	RETURN @ID
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_SIFRE_AC] TO [mediwebuser]
	END TRY
	BEGIN CATCH
	END CATCH
END
GO
