Question : T-SQL -- INSERT Statement Continue On Error

I need to write an INSERT statement,but I want it to continue inserting even if an error is thrown.  If an error does occur, I would like to insert the erroring record into a different table (call it 'error_table').

Answer : T-SQL -- INSERT Statement Continue On Error

try catch will not solve your problem on a bulk insert like that, I was afraid that is what you were trying to do.
If it is not too much data you may try something like this.  I put all the SourceIds into a #tmp table, loop while there are still values in the temp table, pull the TOP 1 to process, try the insert, insert into the error table if it fails, delete that ID from the temp table and END the loop.
I could not fully test this, but it should work.

If it is massive amounts of data look into bulk copy and insert http://msdn.microsoft.com/en-us/library/ms189989.aspx
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
declare @siSourceID int
 
SELECT si.SourceID
INTO #tmpSourceIds
FROM tblSourceInfo si
 
while exists (select 1 from #tmpSourceIds) 
BEGIN 
        SELECT TOP 1 @siSourceID = t.SourceID
        FROM #tmpSourceIds
BEGIN TRY
	INSERT INTO tblInfo
	(
		facility_id,
		sys_loc_code,
		well_id,
		well_status,
		construct_start_date,
		depth_of_well,
		top_casing_elev,
		well_purpose,
		remark
	)
	SELECT 
		   si.facility,
		   si.SourceID, 
		   si.SourceName, 
		   si.Status,
		   si.DrillDate,
		   si.TDW,
		   si.MPE,
		   si.SourceType,
		   si.SourceInfoComments
	FROM tblSourceInfo si
	WHERE si.SourceId = @siSourceID
END TRY
BEGIN CATCH
	INSERT INTO tblErrors
	VALUES (@siSourceID)
END CATCH
 
Delete from #tmpSourceIds where SourceId = @siSourceID;
 
END
Random Solutions  
 
programming4us programming4us