views:

32

answers:

1

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?

A: 

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.

CREATE PROC dbo.usp_VendorUpsert
(
     @stringID INT OUTPUT,
     @stringValue VARCHAR(80)
)
AS
BEGIN

     SET NOCOUNT ON;

     MERGE dbo.Errors as target
       USING (SELECT @stringValue) AS source(ErrorString)
       ON target.ErrorString = source.ErrorString

     WHEN NOT MATCHED THEN
     INSERT (ErrorString) VALUES (@stringValue)

     WHEN MATCHED THEN
     UPDATE SET @stringID = id;

     // Get the id from the insert or the update.
     SET @stringID = COALESCE(SCOPE_IDENTITY(), @stringID);

END

RETURN
womp
THe line WHEN NOT MATCHED THEN INSERT (ErrorString) VALUES (@stringValue)YIELDS ::: Invalid column name 'ErrorString'.
MexDev