Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 Development Tools
 ASP.NET
 Capturing the T-SQL PRINT in .NET

Author  Topic 

graz
Chief SQLTeam Crack Dealer

4149 Posts

Posted - 2004-03-26 : 09:08:15
Has anyone had any luck capturing the results of a T-SQL PRINT statement in .NET (C# specificially)?

===============================================
Creating tomorrow's legacy systems today.
One crisis at a time.

mohdowais
Sheikh of Yak Knowledge

1456 Posts

Posted - 2004-03-26 : 10:47:43
I *think* using a delegate to handle the SqlConnection.InfoMessage event should do the trick. See:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemdatasqlclientsqlconnectionclassinfomessagetopic.asp

OS
Go to Top of Page

TurdSpatulaWarrior
Starting Member

36 Posts

Posted - 2004-03-26 : 11:46:03
Here's some code I came accross that might be of use to you:


using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

public class RaisingInfoMessage
{
public static SqlConnection con;

public static void Main()
{
con = new SqlConnection(
ConfigurationSettings.AppSettings["constring"]
);

con.InfoMessage +=
new SqlInfoMessageEventHandler(InfoMessage);

SqlCommand cmd = new SqlCommand("PRINT 'This is a test'", con);

con.Open();
SqlDataReader reader = cmd.ExecuteReader();

while(reader.Read())
{
Console.WriteLine("{0} - {1}",
reader.GetString(0),
reader.GetString(1));
}

con.Close();

Console.ReadLine();

}

public static void InfoMessage(object sender, SqlInfoMessageEventArgs e)
{
for(int i=0; i < e.Errors.Count; i++)
{
Console.WriteLine("{0} - {1}",
"InfoMessage",
e.Errors[0].ToString());
}
}
}
Go to Top of Page

graz
Chief SQLTeam Crack Dealer

4149 Posts

Posted - 2004-03-26 : 16:46:20
Cool! That code worked like a champ. I did change what I printed out in the InfoMessage though. I printed out Console.WriteLine(e.Message) instead of Errors[i].ToString(). That gave me a cleaner message. YMMV.

===============================================
Creating tomorrow's legacy systems today.
One crisis at a time.
Go to Top of Page
   

- Advertisement -