IF EXISTS ( SELECT * 
            FROM   sysobjects 
            WHERE  id = object_id(N'dbo.CP_DB_CreateUser') 
                   and OBJECTPROPERTY(id, N'IsProcedure') = 1 )
BEGIN
    DROP PROCEDURE dbo.CP_DB_CreateUser 
END
GO

CREATE PROCEDURE dbo.CP_DB_CreateUser
  @NewLogin sysname,
  @DBName sysname
AS
BEGIN
SET NOCOUNT ON;

DECLARE @TSQL nvarchar(MAX);
DECLARE @Return int;
DECLARE @Ver DECIMAL(5,2);

SET @Ver = dbo.CF_DB_Version();

IF NOT EXISTS (SELECT * FROM sys.server_principals WHERE name = @NewLogin AND type_desc = 'SQL_LOGIN')
BEGIN
	RAISERROR('Error creating user not exist LoginToClone', 16, 1);
	RETURN(1);
END

IF @Ver >= 12
	BEGIN TRAN; 

SET @TSQL = 'USE [' + @DBName + ']; IF NOT EXISTS(SELECT name FROM sys.database_principals WHERE name = ''' + @NewLogin + ''') 
                BEGIN
				IF NOT EXISTS(SELECT name FROM sys.database_principals WHERE name = ''' + @NewLogin + ''') 
				    CREATE USER [' + @NewLogin + '] FROM LOGIN [' + @NewLogin + '];
				END;';
EXEC @Return = sp_executesql @TSQL;

IF (@Return <> 0)
BEGIN
	IF @Ver >= 12
		ROLLBACK TRAN;
	RAISERROR('Error creating user', 16, 1);
	RETURN(1);
END;

IF @Ver >= 12
	COMMIT TRAN;
END;