我想仅在不存在的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)
如何打印错误,我想对此进行错误处理。如果有重复..应该打印消息。
答案 0 :(得分: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
答案 1 :(得分: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;