I have an application that monitors a process and “learns” exceptions, by adding them to a DB. The process to gather the errors/exceptions is pretty solid, but not the storing on the DB side.
What I want to accomplish is something like
public int GetErrorId(string StringToClassify)
{
sql = "SELECT [id] FROM [DBNAME].[dbo].[ERRORS] WHERE [ErrorString] = (@StringToClassify)";
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.Parameters.Add("@StringToClassify", SqlDbType.VarChar);
cmd.Parameters["@StringToClassify"].Value = StringToClassify;
connection.Open();
Object result = cmd.ExecuteScalar();
if (result == null)
sysId = AddError(StringToClassify);
else
sysId = Int32.Parse(result.ToString());
}
}
How do I implement the AddError(string s) function? Something that inserts a record and returns the ID of the inserted record?
If there is no other logic that depends on whether the string existed or not, why not make it into a stored procedure that does an INSERT if it’s present, or an UPDATE if it’s not? Then return the ID either way.
If you’re using SQL Server 2008, this is a perfect opportunity to use the MERGE statement.
Here’s an example of a stored procedure, utilizing the MERGE statement, that will “upsert”, modified from this example.