存储过程不要使用IF EXISTS 使用@RecordCount = count(1) 查询是否存在数据

业务需求:在存储过程中保存前判断:是否数据库中已经存在要存储的条码信息,如果存在,则抛出提示信息,不存储

错误代码

		declare k cursor  for
		select   BarCode from tblLineSideTransactionDetail  where FormNo = @FormNo
		OPEN K
		FETCH NEXT FROM K INTO @BarCode
		while @@Fetch_status=0
		begin

        IF EXISTS(
		select BarCode from tblLineSideTransactionDetail where BarCode=@BarCode
			and (Received=1 or OutStore=1)
        )


		begin
			set @Results='999'
			set @Msg='条码:['+@BarCode+']已经入库或退库!'
			return
		end
		FETCH NEXT FROM K INTO @BarCode
		END 
		CLOSE K
		deallocate K

该代码IF EXISTS 无法走,不知道为什么

修改成

		declare  @Recordcount int

    declare k cursor  for
		select   BarCode from tblLineSideTransactionDetail  where FormNo = @FormNo
		OPEN K
		FETCH NEXT FROM K INTO @BarCode
		while @@Fetch_status=0
		begin

		select @Recordcount = COUNT(1) from tblLineSideTransactionDetail where BarCode=@BarCode
			and (Received=1 or OutStore=1)

		IF(@Recordcount > 0)
		begin
			set @Results='999'
			set @Msg='条码:['+@BarCode+']已经入库或退库!'
			return
		end
		FETCH NEXT FROM K INTO @BarCode
		END 
		CLOSE K
		deallocate K

你可能感兴趣的:(数据库)