简体   繁体   中英

Get SQL print messages from stored proc

I have a stored proc that outputs print messages to the message tab. I want to grab these and display them back to the user once the proc has finished.

Here is what i'm trying but it's coming back empty. It's also not because i'm clearing the StringBuilder. I moved the clear into Open and still gives the same results.

private static void conn_InfoMessage(object sender, SqlInfoMessageEventArgs e)
{
    sqlMessages.AppendLine(e.Message);
}

private static void Open()
{
    if (conn.State.Equals(ConnectionState.Closed))
    {
        conn.InfoMessage += conn_InfoMessage;
        conn.Open();
    }
}

private static void Close()
{
    if (conn.State.Equals(ConnectionState.Open))
    {
        conn.InfoMessage -= conn_InfoMessage;
        sqlMessages.Clear();
        conn.Close();
    }
}

public static string RemoveContacts(int customerCode)
    {
        try
        {
            Open();
            using (SqlCommand cmd = conn.CreateCommand())
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "s_RemoveAllCustomerContacts";
                cmd.Parameters.AddWithValue("@customerCode", customerCode);
                cmd.ExecuteNonQuery();
                return sqlMessages.ToString();
            }
        }
        catch (SqlException ex)
        {
            throw new ArgumentException(ex.Message);
        }
        finally
        {
            Close();
        }
    }

Ok so I figured out my answer and had to use the following

private static void conn_InfoMessage(object sender, SqlInfoMessageEventArgs e)
    {
        if (e.Errors != null)
        {
            for (int i = 0; i < e.Errors.Count; i++)
            {
                sqlMessages.AppendLine(e.Errors[i].Message);
            }
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM