To catch specific SQLExceptions using Microsoft.NET and Microsoft Sequel Server you can use the snippet below. You also need to look for the specific error numbers/codes you want to catch. To do this you can either execute the following query in the SQL Management Studio or you can use this
List of SQLException Numbers/Codes (Direct-DL around 15mb).

Samples

T-SQL Sample

SELECT * FROM master.dbo.sysmessages ORDER BY error ASC

C# Sample

private static void MySqlMethod()
{
	SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder
	{
		DataSource = "localhost",
		InitialCatalog = "Northwind",
		IntegratedSecurity = true
	};

	try
	{
		using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
		{
			connection.Open();
			using (SqlCommand command = connection.CreateCommand())
			{
				//inserting invalid sql (for example: column not exists)
				command.CommandText = "SELECT InvalidColumnName FROM Customers";
				command.ExecuteNonQuery();
			}
		}
	}
	catch (SqlException ex)
	{
		// Log the original exception here
		foreach (SqlError sqlError in ex.Errors)
		{
			switch (sqlError.Number)
			{
				case 207: // 207 = InvalidColumn
					//do your Stuff here
					break;
				case 547: // 547 = (Foreign) Key violation
					//do your Stuff here
					break;
				case 2601: // 2601 = (Primary) key violation
					//do your Stuff here
					break;
				default:
					//do your Stuff here
					break;
			}
		}
	}
}

VB.NET Sample

Private Sub MySqlMethod()
	Dim builder As New SqlConnectionStringBuilder() With { _
		.DataSource = "localhost", _
		.InitialCatalog = "Northwind", _
		.IntegratedSecurity = True _
	}

	Try
		Using connection As New SqlConnection(builder.ConnectionString)
			connection.Open()
			Using command As SqlCommand = connection.CreateCommand()
				'inserting invalid sql (for example: column not exists)
				command.CommandText = "SELECT InvalidColumnName FROM Customers"
				command.ExecuteNonQuery()
			End Using
		End Using
	Catch ex As SqlException
		' Log the original exception here
		For Each sqlError As SqlError In ex.Errors
			Select Case sqlError.Number
				Case 207
					' 207 = InvalidColumn
					'do your Stuff here
					Exit Select
				Case 547
					' 547 = (Foreign) Key violation
					'do your Stuff here
					Exit Select
				Case 2601
					' 2601 = (Primary) key violation
					'do your Stuff here
					Exit Select
				Case Else
					'do your Stuff here
					Exit Select
			End Select
		Next
	End Try
End Sub

Compatibility: working .NET 2.0 working .NET 3.0 not tested .NET 3.5 not working .NET 4.0 not working .NET 4.5not working .NET 4.6

If you have any questions or suggestions feel free to rate this snippet, post a comment or Contact Us via Email.

Related links:

Leave a Reply