Reputation: 125
I'm running an SQL stored procedure which inserts records into a table from 2 different tables. Since there is a primary key constraint on the table that is being inserted, the exception Duplicate key was ignored
raises. But when I call the SP from my C# windows form application this raises the exception and the execution stops. How do I handle this? My C# code is below:
qry = "Exec Database.dbo.spname '" + searchvalue + "'";
if (rs.State == 1) {
rs.Close();
}
rs.Open(qry, sqltbl.GetSqlConnection());
I get an exception error on the rs.Open
line
Upvotes: 0
Views: 625
Reputation: 14189
Seems that the exception is being thrown from the procedure Database.dbo.spname
you are executing. Exceptions aren't something you should ignore or hide under the couch.
You probably have a statement like the following:
INSERT INTO SomeTable (
KeyColumn,
ColumnName)
SELECT
I.InsertingKeyColumn,
I.ColumnName
FROM
SomeOtherTable AS I
Make use of the NOT EXISTS
to check existance of records before trying to insert and the error won't pop up.
INSERT INTO SomeTable (
KeyColumn,
ColumnName)
SELECT
I.InsertingKeyColumn,
I.ColumnName
FROM
SomeOtherTable AS I
WHERE
NOT EXISTS (SELECT 'not yet in SomeTable' FROM SomeTable AS S WHERE I.InsertingKeyColumn = S.KeyColumn)
Upvotes: 1