ALTER FUNCTION [dbo].[GENERATE_MEMBERSHIP_ID]
(
	@agentId INT
)
RETURNS VARCHAR(20)

BEGIN
DECLARE @MEMBESHIP_ID VARCHAR(15) ,@RANDOM_NUMBER VARCHAR(12), @maxValue INT

SELECT
				@maxValue = ISNULL(maxValue, 1)
				
			FROM agentMaster (NOLOCK) WHERE  AGENTID = @AGENTID



SELECT @RANDOM_NUMBER = RIGHT('0000000' + CAST(@maxValue AS VARCHAR), 6)

		SET @MEMBESHIP_ID = 'IME' + @RANDOM_NUMBER
		
		RETURN @MEMBESHIP_ID;
END

SELECT dbo.GENERATE_MEMBERSHIP_ID('394390')
--select maxvalue, * FROM agentMaster where agentid='394390'




UPDATE customerMaster set membershipid=dbo.GENERATE_MEMBERSHIP_ID('394390') WHERE membershipid IS NULL