如果值不存在,则插入SQL

时间:2017-06-01 20:00:28

标签: sql sql-server tsql

所以我需要在表中插入值,但如果存在这些值,我希望我的脚本不插入任何内容。我已经解决了很多问题,但是我的插入语句让我陷入困境。

DECLARE @billableitemID int;
set @billableitemid = (select billableitemID from dbo.treatment where 
@billableitemid=treatment.id)
set @billableitemID = 256



CREATE TABLE #MembershipBenefitItem
    ( BenefitID int ,
      BillableItemTypeID int ,
      BillableItemID  int
    )

INSERT INTO #MembershipBenefitItem
    ( BenefitID ,
      BillableItemTypeID ,
      BillableItemID 
    )

 VALUES  (23450,1,@billableitemid),
(57256,1,@billableitemid)

select m.* from #MembershipBenefitItem  AS M
left join membershipbenefititem AS M1 on m.billableitemid= m1.billableitemid 
and m.billableitemtypeid= m1.billableitemtypeid 
and m.benefitid= m1.benefitID
and M1.billableitemID=@billableitemID and M1.billableitemtypeID=1 and 
M1.benefitID IN(23450,57256)  
where M1.ID is null

INSERT INTO MembershipBenefitItem
    ( BenefitID,
      BillableItemTypeID,
      BillableItemID 
    )

 select m.BenefitID, m.BillableItemTypeID, m.BillableItemID from 
#MembershipBenefitItem  AS M
left join membershipbenefititem AS M1 on m.billableitemid= m1.billableitemid 
 and m.billableitemtypeid= m1.billableitemtypeid 
 and m.benefitid= m1.benefitID
and M1.billableitemID=@billableitemID and M1.billableitemtypeID=1 and 
M1.benefitID IN(23450,57256) 
where M1.ID is null



DROP TABLE #MembershipBenefitItem

1 个答案:

答案 0 :(得分:1)

这似乎是使用Merge语句的好例子。

https://docs.microsoft.com/en-us/sql/t-sql/statements/merge-transact-sql

看起来像是:

MERGE MembershipBenefitItem AS trg
USING #MembershipBenefitItem AS src 
ON src.BillableItemID = trg.BillableItemID --and other join conditions
WHEN NOT MATCHED BY TARGET THEN 
INSERT (col1, col2, col3) -- this will be inserted into trg table
VALUES (src.val1, src.val2, src.val3)