i need find efficient way insert value table when value not in table.
here sample table:
declare @table table (thevalue int primary key) sample data insert:
insert @table select 1 union select 2 union select 3 --existing data declare @x int;set @x=5 --data add here ideas can think of this. 1 best and/or there better way? batch process, there no risk of process inserting data, no locking necessary in try 1.
try 1:
if not exists (select 1 @table thevalue=@x) begin insert @table values (@x) end try 2:
insert @table select @x except select thevalue @table try 3:
insert @table select @x @x not in (select thevalue @table) try 4:
begin try insert @table values (@x) end try begin catch end catch
here's 1 other way self joining table inserting , inserting records doesn't exist.
first table doing batch inserts to, want maintain unique records. keep in mind should have unique constraint on here. want use 1 of these unique inserts never run constraint:
declare @table table (thevalue int primary key) one of tables getting data want insert main batch table:
declare @tableselectingfrom table (thevalue int primary key) for example, populating record:
insert @tableselectingfrom select 1 there's left outer join pull unique records @tableselectingfrom:
insert @table select a.thevalue @tableselectingfrom left join @table b on a.thevalue = b.thevalue b.thevalue null select * @table
Comments
Post a Comment