使用存储过程如果存在或不存在,检查给定ID是否存在?

时间:2014-11-26 09:38:31

标签: sql-server stored-procedures

我正在使用存储过程在数据库中进行插入,更新,删除操作。要检查给定的ID是否存在,我在代码中使用if exists条件。这是我的问题:我获得了数据库中的ID,但条件检查并允许将重复值存储在数据库中。

我的存储过程代码:

SET NOCOUNT ON;

If @Action = 'Insert'   --used to Insert records
Begin
    If Exists(select BatchNo from Work_In_Progress where BatchNo = '@BatchNo')
    Begin
        set @Error='Already Exists'     
    End     
    Else 
    Begin                  
        insert into Work_In_Progress 
        values (@BatchNo, @ISR_No, @CatalogNo, @Brandname, @Productname, @Operation_Code, @Operation_Name, @Machine_Id, @Received_Qty, @Finished_Qty, @Balance_Qty, @Accepted_Qty, @Rejected_Qty, @Startdate, @Starttime, @Enddate, @Endtime, @Accp_MTS_No, @Rej_MTS_No, @Remarks, @Work_Done_By, @Approved_By, @Updated_Date, @Updated_By, @InspectionStatus);

        insert into Sample_Inspection   
        values(@BatchNo,@Operation_Code,@Inspection_Name,@Insp_Parameter,@Insp_Tolerance,@Observation,@Sample_Rcd_Qty,@Sample_Accepted_Qty,@Sample_Rejected_Qty,@Sample_Rework_Qty,@Sample_Accp_MTS_No,@Sample_Rej_MTS_No,@Sample_Rework_MTS_No,@Sample_Remarks,@Sample_WorkDone_By,@Sample_WorkDone_Date,@Sample_Approved_By,@Sample_Updated_Date,@Sample_Updated_By);
   End
End

我如何克服这个问题?

2 个答案:

答案 0 :(得分:0)

declare @id int =null,
@ret int=null
if Not exists(select id from table1 where id=@id)
begin
 --insert query,
     --set  @ret=@id
     end
      else 
   begin
    ---set  @ret=-1
    end

答案 1 :(得分:0)

@BatchNo附近没有引号的情况下执行此操作:

If Exists(select BatchNo from Work_In_Progress where BatchNo = @BatchNo)