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

CREATE PROCEDURE [dbo].[CP_Turno_DesAsignar] (
	@Id_Turno				INT
	) 

AS
 
DECLARE @Mensaje				VARCHAR(100)
DECLARE @Id_Turno_Acomp			INT			


BEGIN TRY
BEGIN TRAN

	UPDATE CRM_Turnos SET Estado = '', Id_Cliente = 0, Fecha_Asignacion = NULL, Tipo_Reserva =NULL WHERE Id_Turno=@Id_Turno

	
	DECLARE curNombre CURSOR FOR
	SELECT  ISNULL(Id_Turno_Tomado, '') 
			FROM CRM_Turnos_Clientes
			WHERE
			Id_Turno=@Id_Turno

	OPEN curNombre
	FETCH NEXT FROM curNombre INTO @Id_Turno_Acomp
	WHILE @@FETCH_STATUS = 0
	BEGIN

		UPDATE CRM_Turnos SET Estado = '', Id_Cliente = 0, Fecha_Asignacion = NULL, Tipo_Reserva =NULL WHERE Id_Turno=@Id_Turno_Acomp
		DELETE CRM_Turnos_Clientes WHERE Id_Turno=@Id_Turno

	FETCH NEXT FROM curNombre INTO @Id_Turno_Acomp
	END
	CLOSE curNombre
	DEALLOCATE curNombre

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

END TRY  


BEGIN CATCH  
    EXECUTE usp_GetErrorInfo;  
	ROLLBACK
END CATCH;   
