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


CREATE PROCEDURE [dbo].[CP_Turno_Invitados] (
	@Apellido   VARCHAR(100),	
	@Nombre	    VARCHAR(100),
	@Documento  VARCHAR(100),
	@Email		VARCHAR(100),
	@Obs		VARCHAR(2000),
	@Fecha_Nac	DATETIME
	)
AS

------------INICIO DE VARIABLES LOCALES-----------

DECLARE @Existe_Id_Cliente			INT
DECLARE @Existe						INT
DECLARE @Categoia					VARCHAR(40)

------------FIN DE VARIABLES LOCALES--------------

SELECT @Existe				= COUNT(*) FROM Clientes WHERE Doc_Nro = CAST(@Documento AS BIGINT) AND Activo = 1
SELECT @Existe_Id_Cliente	= Id_Cliente FROM Clientes WHERE Doc_Nro = CAST(@Documento AS BIGINT) AND Activo = 1

----------------------------------------------------

SET @Fecha_Nac = REPLACE(@Fecha_Nac,'-','')

SET @Categoia = dbo.CF_xParam('Categ_Invitados')

----------------------------------------------------

IF (ISNULL(@Existe,0 ) <> 0)
BEGIN

SET @Existe  = @Existe

SELECT  0 AS ErrorNumber
			,0 AS ErrorSeverity
			,0 AS ErrorState
			,0 AS ErrorProcedure
			,0 AS ErrorLine
			,401 AS ErrorMessage
END
ELSE
BEGIN TRY
BEGIN TRAN

	SET @Existe  = (SELECT MAX(Id_Cliente) FROM Clientes ) + 1

	INSERT INTO Clientes (Razon_Social,	  Apellido,			Nombre,			Id_Tipo_Doc,	Doc_Nro,
						 Email,			  Email_Cob,		Email_Web,		Activo,			Id_Iva,
						 Id_Tipo_Cli,	  Fecha_Alta,		Tipo_Persona,	Id_Cliente,		ID_NACIONALIDAD,
						 ID_LISTA_PRECIO, Id_Cliente_Ref,	Observacion,	Fecha_Nac)

				VALUES (LTRIM(RTRIM(UPPER(@Apellido))) +' '+ LTRIM(RTRIM(UPPER(@Nombre))),UPPER(@Apellido),UPPER(@Nombre),'DNI',@Documento,
						 @Email,			@Email,			@Email,			1,				'CF',
						@Categoia, 			GETDATE(),		'F',			@Existe,		'ARG',
						0,					0,				@Obs,			@Fecha_Nac)

	
               
	COMMIT
	SELECT  0 AS ErrorNumber
			,0 AS ErrorSeverity
			,0 AS ErrorState
			,0 AS ErrorProcedure
			,0 AS ErrorLine
			,CAST(@Existe AS VARCHAR(4000)) AS ErrorMessage

END TRY

BEGIN CATCH
EXECUTE usp_GetErrorInfo;
ROLLBACK
END CATCH;	
	
		
	