I have a stored procedure that can return both a PRINT
message and regular query results from a SELECT
statement. Using the elegant solution provided in this thread, I can easily capture my PRINT
message when invoking SqlCommand.ExecuteNonQuery()
in my C# code. The problem is, I also want to return my result set.
When I use a SqlDataReader
to get back the query results from my stored proc using SqlCommand.ExecuteReader
, the event handler that captures my PRINT
message never fires like it does when I use SqlCommand.ExecuteNonquery
.
It's beginning to seem like I can only have one or the other. Is there a way for me to capture both my PRINT
message and my query results?
Here's a snippet of my SQL stored procedure:
IF EXISTS
(
SELECT MFG_PART_NUMBER, COUNT(*) AS RecordCount
FROM [PartsManagement].[ManufacturerCatalogPart]
WHERE CatalogID = @CatalogID
GROUP BY MFG_PART_NUMBER
HAVING COUNT(*) > 1
)
BEGIN
SELECT MFG_PART_NUMBER, COUNT(*) AS RecordCount
FROM [PartsManagement].[ManufacturerCatalogPart]
WHERE CatalogID = @CatalogID
GROUP BY MFG_PART_NUMBER
HAVING COUNT(*) > 1;
PRINT 'The update was not executed because duplicate MFG_PART_NUMBERs were found in the catalog. Delete the duplicates and try again.';
END;
And here's a snippet from my code:
//field
private string sqlPrintMessage = "";
//event handler for sql PRINT message
void myConnection_InfoMessage(object sender, SqlInfoMessageEventArgs e)
{
sqlPrintMessage = e.Message;
}
public void SomeMethod()
{
using (SqlConnection sqlcon = new SqlConnection(ConnectionManager.GetConnectionString()))
{
sqlcon.InfoMessage += new SqlInfoMessageEventHandler(myConnection_InfoMessage);
SqlCommand sqlcmd = new SqlCommand("[ManufacturerCatalogUpdate].[CheckCatalogForDuplicates]", sqlcon);
sqlcmd.CommandType = CommandType.StoredProcedure;
sqlcmd.Parameters.AddWithValue("@CatalogID", catalogID);
sqlcon.Open();
//SqlDataReader reader = sqlcmd.ExecuteReader();
sqlcmd.ExecuteNonQuery();
if (sqlPrintMessage == "") //then proceed with update
{
//do some logic
}
else
{
//System.Diagnostics.Debug.WriteLine(sqlPrintMessage);
//List<DuplicatePartCount> duplicateParts = new List<DuplicatePartCount>();
//while (reader.Read())
//{
// DuplicatePartCount record = new DuplicatePartCount();
// record.MFG_PART_NUMBER = reader.GetString(0);
// record.count = reader.GetInt32(1);
// duplicateParts.Add(record);
//}
}
}
}