答案 0 :(得分:2)
并不是InfoMessage事件只被触发一次,而是SQL Server不会立即发送PRINT输出。您可以尝试使用带有NOWAIT选项的RAISERROR;
RAISERROR ('My message', 0, 1) WITH NOWAIT
使用严重性低于11的RAISERROR不会被视为错误条件。
编辑:完成工作示例
我已经整理了一个完整的工作示例。我是一个C#家伙而不是VB家伙,抱歉。请务必阅读连接的FireInfoMessageEventOnUserErrors属性。这是我简单的SP;
create proc dbo.MyProc as
begin
waitfor delay '00:00:05'
raiserror('Hello One', 16, 1) with nowait
waitfor delay '00:00:05'
raiserror('Hello Two', 1, 1) with nowait
waitfor delay '00:00:05'
raiserror('Hello Three', 1, 1) with nowait
end
这是我的简单控制台应用程序;
namespace RaiserrorNoWait
{
using System;
using System.Data;
using System.Data.SqlClient;
class Program
{
static void Main()
{
using (SqlConnection connection = new SqlConnection(@"Integrated Security=SSPI;Initial Catalog=Scratch;Data Source=UKCP0758\DEVSQL"))
{
connection.InfoMessage += connection_InfoMessage;
connection.FireInfoMessageEventOnUserErrors = true;
connection.Open();
using (SqlCommand command = new SqlCommand("dbo.MyProc", connection))
{
command.CommandType = CommandType.StoredProcedure;
Console.WriteLine("{0} - {1}", DateTime.Now, "Execute query...");
command.ExecuteNonQuery();
Console.WriteLine("{0} - {1}", DateTime.Now, "Query finished.");
}
connection.Close();
}
Console.WriteLine("Press Enter to Exit.");
Console.ReadLine();
}
static void connection_InfoMessage(object sender, SqlInfoMessageEventArgs e)
{
// Should check for both real errors and info messages.
Console.WriteLine("{0} - Query message: {1}", DateTime.Now, e.Message);
}
}
}
运行这个我得到这个输出,注意在整个SP执行过程中收到的消息。
17/02/2015 11:29:31 - Execute query...
17/02/2015 11:29:36 - Query message: Hello One
17/02/2015 11:29:41 - Query message: Hello Two
17/02/2015 11:29:46 - Query message: Hello Three
17/02/2015 11:29:46 - Query finished.
Press Enter to Exit.