Click here to Skip to main content
15,892,737 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello Experts

Consider the below Database:
SQL
Create	Database	Test
Go
Use	Test
Go
Create	Table	table1	(
ID	BigInt	Identity	Not Null	Primary Key,
Title	nVarchar(50)		Not Null	Unique
)
Go
Insert	table1	(Title)
	Values	(N'title1')
Go


Here is my question that what code I can use to log the incompatible recordes and continue with correct records.
For example consider this query:
SQL
Insert	table1	(Title)
	Select	N'title2'
		Union
	Select	N'title1'  

As you know, no record will affect.
Is there any query that inserts the 'title2' and Prints the inserting error of 'title1' ?
Posted

1 solution

Your issue is not clear enough.

First of all, i would suggest you to read below articles:
Error Handling in T-SQL: From Casual to Religious[^]
Using TRY...CATCH in Transact-SQL[^]
SQL Server Error Handling Workbench[^]
Handling Errors in Stored Procedures[^]
SQL Server 2005 Try and Catch Exception Handling[^]

Secondly, you can check for existing records in a 3 ways:
1) using EXISTS[^] statement.
2) using SELECT with IN[^] or NOT IN option
3) looping through the set of records (using WHILE[^] statement or CTE[^] /Common Table Expressions/)


Example:
SQL
INSERT INTO Table2 (Title)
SELECT Title
FROM (SELECT 'Title1' UNION ALL
      SELECT 'Title2' UNION ALL) AS T
WHERE T.Title NOT IN (SELECT Title FROM Table2)

NOTE: Above query is not optimal and time of execute is very long in case of large data amount.
 
Share this answer
 
v2
Comments
Meysam Toluie 18-Nov-13 2:41am    
Thank you for your time.
In your example you handle the error of multiple records; But what about the other errors.
There are many kind of queries that I can not think about all possible errors.
Did you get it?
Maciej Los 18-Nov-13 9:03am    
I can't get you ;( Error handling is not enough for you?
Meysam Toluie 18-Nov-13 15:08pm    
It is enough when you know what kind of error will occur; anyway thank you for your time.
Maciej Los 19-Nov-13 4:27am    
You're welcome ;)
Remember, you can catch any kind of error using Try..Catch block ;) similar to the exception-handling features of the MS Visual C++ or/and C# languages

Have a nice day!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900