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



CREATE PROCEDURE [dbo].[CP_Transacciones_Generar]
@pId_Usuario SMALLINT
AS

/*Declaracion Variables Locales*/
DECLARE @Flag_Existe_Usuario	TINYINT
DECLARE @Id_Trans				INT
DECLARE @Descripcion			VARCHAR(50)
DECLARE @Fecha_Mov				DATETIME
DECLARE @Mensaje				VARCHAR(100)
/*Fin de Declaraciones Variables Locales */

PRINT 'Procedimiento: CP_Transacciones_Generar Id_Usuario: '+ CAST(@pId_Usuario AS VARCHAR(10))

BEGIN TRY
	BEGIN TRAN

	SET @Flag_Existe_Usuario = ISNULL((SELECT 1 FROM Seg_User WHERE No = @pId_Usuario), 0)
	IF (@Flag_Existe_Usuario = 0)
	BEGIN
		SET @Mensaje = 'No existe el usuario '

		SELECT	1001			AS ErrorNumber 
				,0				AS ErrorSeverity  
				,0				AS ErrorState 
				,0				AS ErrorProcedure  
				,0				AS ErrorLine		
				,@Mensaje		AS ErrorMessage
				,0				AS Id_Trans
		ROLLBACK
		RETURN 1001
	END

	SET @Descripcion	= 'CP_Transacciones_Generar'
	SET @Fecha_Mov		= GETDATE()
	SET @Id_Trans		= ISNULL((SELECT MAX(Id_Trans) + 1 FROM Transacciones), 0)

	INSERT INTO dbo.Transacciones
	(Id_Trans,		Descripcion,	Fecha_Mov,
	Id_Usuario)
	VALUES
	(@Id_Trans,		@Descripcion,	@Fecha_Mov,
	@pId_Usuario)

	COMMIT

	SET @Mensaje = @Descripcion

	SELECT	 0				AS ErrorNumber 
			,0				AS ErrorSeverity  
			,0				AS ErrorState 
			,0				AS ErrorProcedure  
			,0				AS ErrorLine		
			,@Mensaje		AS ErrorMessage
			,@Id_Trans		AS Id_Trans

END TRY  


BEGIN CATCH  
    SELECT  ERROR_NUMBER() AS ErrorNumber  
		,ERROR_SEVERITY() AS ErrorSeverity  
		,ERROR_STATE() AS ErrorState  
		,ERROR_PROCEDURE() AS ErrorProcedure  
		,ERROR_LINE() AS ErrorLine  
		,ERROR_MESSAGE() AS ErrorMessage
		,@Id_Trans		AS Id_Trans 

	ROLLBACK
	RETURN 9999
END CATCH

PRINT 'FIN Procedimiento: CP_Transacciones_Generar Trans: '+ CAST(@Id_Trans AS VARCHAR(10))
RETURN 0
