if exists(select 1 from sysobjects where name='pr_wxsf_orderback_return_giftcert')
  drop procedure pr_wxsf_orderback_return_giftcert
go



CREATE PROCEDURE pr_wxsf_orderback_return_giftcert
(
	@orderno VARCHAR(50),		--线上订单号
	@giftcert_no VARCHAR(50),	--礼品号
	@code CHAR(1) OUT,			--（0：失败  1：成功）
	@message VARCHAR(100) OUT	--（失败message）
)	
AS 
BEGIN
	/*
	--[status]:1 可用；2 已用；4 作废 3不可用 0 搁置5已过期
	*/
	--SET XACT_ABORT ON
	BEGIN TRANSACTION
	IF @giftcert_no = '' OR @giftcert_no IS NULL
	BEGIN
		IF exists (SELECT 1 FROM t_rm_gift_certificate WHERE flow_no = @orderno)
		BEGIN
			update t_rm_gift_certificate 
			set [status]='1',pay_oper= null,pay_date=null,flow_no=null,pay_branch=null,memo1=null
			WHERE flow_no=@orderno  			
			IF @@ERROR <> 0
			BEGIN
				SET @message = '更新礼券状态失败，请检查['+@orderno+']单是否使用了礼券!'
				GOTO my_err
			END
		END			 
	END
	ELSE
	BEGIN
		update t_rm_gift_certificate 
		set [status]='1',pay_oper= null,pay_date=null,flow_no=null,pay_branch=null,memo1=null
		WHERE flow_no=@orderno 
		AND giftcert_no = @giftcert_no		
		IF @@ERROR <> 0
		BEGIN
			SET @message = '更新礼券状态失败，请检查['+@orderno+']单是否使用了礼券['+@orderno+']!'
			GOTO my_err
		END
	END
	
	COMMIT TRANSACTION
	SET @code = '1'
	SET @message = '处理礼券成功！'	
	RETURN
	
	my_err:
		ROLLBACK TRANSACTION
		SET @code = '0'
		RAISERROR(@message,16,1)
		RETURN
END
go