0

我只想在 field_tag 值不存在时才插入表中。我想在插入表之前检查..如果收据之前存在于相同的 field_tag 值下。如果不存在,那么只有我想插入。我正在使用 sql server 2008

INSERT INTO [INVENTORY].[TBL_RECEIPTS]
           ([TicketNbr]
       ,[RevisionNbr]
           ,[Location_ID]
           ,[ContractNumber]
           ,[Storage_ID]
       ,[VarietyID]
           ,[GrossWeight]
           ,[TareWeight]
           ,[Carrier]
           ,[Receipt_date]
           ,[Last_update]
           ,[Inv_weight]
       ,[SAPBatch]
       ,[MoistureFactor]
       ,[Load_Harvested]
       ,[FIELDID]
       ,[GROWER_LOAD_NBR]
       ,[HARVEST_NBR]
       ,[TRACE_WORMS]
       ,[COR_CERT]
       ,[GFF_DEST]
---    ,[GFF_CONTRACT]
       ,[CAB_ID]
       ,[sOURCE]
       ,[CREATED_BY]
       ,[TOTALBONUSES]
       ,[PIDNUMBER] 
       ,[CARRIERVENDORID]
       ,[HAUL_ZONE]
       ,[FIELD_Tag]
       ,[Station]
       ,[COUNTY]
       ,[GradeDate]
       ,[Load_Received]
       ,[Load_Processed]

)
     VALUES
           (@CERT
      ,@RevisionNbr
           ,@Location_ID
           ,@ContractNUmber
           ,@Storage_ID
       ,@VarietyID
           ,@Gross_Weight
           ,@TareWeight
           ,@CarrierName
           ,@receipt_date
           ,Getdate()
           ,@Inv_weight
       ,@receiptbATCHnbr
       ,@DockageWeight
       ,@HARVEST_DT
       ,@FIELDID
       ,@GROWER_LOAD_NBR
       ,@HARVEST_NUMBER
       ,@TRACE_WORMS    
       ,@COR_CERT
       ,@GFF_DEST
---    ,@CONTRACT
       ,@CAB_ID
       ,'I'
       ,'Scale Interface'
       ,0
       ,@ContractPIDNumber
       ,@CARRIERID
       ,@HAUL_ZONE
       ,@FIELD_TAG
       ,@STATION
       ,@COUNTY
       ,@GRADE_DT
       ,@Arrival_dt
       ,@current_Date
)

我确实喜欢这样:

insert into yourtable
(field1, field2, etc)
select value1, value2, etc
where not exists
( SELECT * FROM [INVENTORY].[TBL_RECEIPTS] WHERE Field_Tag = @FIELD_TAG)

如何打印错误,我想对此进行错误处理。如果重复存在..它应该打印消息。

4

2 回答 2

3

像这样的东西应该工作。

insert into yourtable
(field1, field2, etc)
select value1, value2, etc
where not exists
(subquery to specify
condition under which you don't insert record)

编辑从这里开始

如果记录已经存在,另一种通知用户的方法

declare @Records as int;
set @Records = select count(*) from tbl_receipts
where field_tag = @Field_Tag;

if @Records > 0
begin
select 'record exists'
end

else
begin
insert query
select 'record added'
end
于 2013-04-01T23:16:40.560 回答
0

它处于工作状态,请测试它。如果没有 imei=69212 和 description='dfhjsdfh' 的条目,将在数据库中输入 insert into events select 1,2,3 from ( select 1 from events where not exists ( select 1 from events where imei=69212 and description='dfhjsdfh' group by imei) group by imei) AS tt;

于 2014-12-15T18:35:54.757 回答