SET NOCOUNT ON 

DECLARE @ErrorTag NVARCHAR(20) 
SET         @ErrorTag = '###ERROR###'

DECLARE @WarningTag NVARCHAR(20) 
SET         @WarningTag = '###WARNING###'

DECLARE @AdviceTag NVARCHAR(20) 
SET         @AdviceTag = '###ADVICE###'

DECLARE @HeaderTag NVARCHAR(20) 
SET         @HeaderTag = '###HEADER###'

DECLARE @DataTag NVARCHAR(20) 
SET         @DataTag = '###DATA###'

DECLARE @DescTag NVARCHAR(20) 
SET @DescTag = '###DESCRIPTION###'

DECLARE @colSeperator NVARCHAR(20) 
SET         @colSeperator = ':,:'

DECLARE @CurFlag  INTEGER 
SET         @CurFlag  = 0 

DECLARE @LoginCount        INTEGER 
SET         @LoginCount        = 0

DECLARE @errorCode  INTEGER 
SET         @errorCode  = 0

DECLARE @retCode  INTEGER 
SET         @retCode    = 0

DECLARE @userName nvarchar(256) = ''
DECLARE @counts integer = 0

DECLARE @dupeLogins TABLE
(
		UserName nvarchar(256),
		Counts integer
)

PRINT @DescTag + ' Check for duplicate login names'

INSERT INTO @dupeLogins
SELECT login, count(*) from UMUSERS with(nolock) group by login having count(*) > 1


SELECT @errorCode   = @@ERROR, @LoginCount = @@ROWCOUNT
IF  @errorCode != 0 GOTO CX_EXIT 

--No duplicate logins are found.
IF @LoginCount = 0 
BEGIN 
    SET @retCode = 0
    PRINT 'No duplicate logins found'
	SET @errorCode = 0

    GOTO CX_EXIT
END 

--If duplicate logins are found:
SET @retCode = 2
PRINT @ErrorTag + ' Found one or more logins with duplicate entries'

--Print Header
PRINT @HeaderTag + ' Login:,:Count:'
PRINT '-----------------------------------------------------'
    
DECLARE Cur CURSOR STATIC FOR 
SELECT UserName, counts from @dupeLogins

SET @errorCode  = @@ERROR 
IF  @errorCode != 0 GOTO CX_EXIT 

SET @CurFlag = 1 
OPEN Cur 

SET @errorCode  = @@ERROR 
IF  @errorCode != 0 GOTO CX_EXIT 

FETCH NEXT 
FROM  Cur 
INTO  @userName, @counts 

SET @errorCode  = @@ERROR 
IF  @errorCode != 0 GOTO CX_EXIT 

WHILE @@FETCH_STATUS = 0 
BEGIN 
    PRINT @DataTag + ' ' + @userName + ':,:' + CAST(@counts AS NVARCHAR(3))

    FETCH NEXT 
    FROM  Cur
    INTO  @userName, @counts 
END 

SET @errorCode = 1
--Print Advice
PRINT @AdviceTag + ' Please update accounts with duplicate login names so that the login names are unique'

CX_EXIT: 

IF @CurFlag = 1 
BEGIN 
    CLOSE       Cur 
    DEALLOCATE  Cur 
END

IF @errorCode != 0
    SELECT 2
ELSE
    SELECT @retCode

RETURN