所以这是一个非常有趣的问题。大约 5 年前我尝试过,但没有成功,所以这对我来说是一个小挑战 :) 好吧,这就是我为你准备的。
要从 SQL Server 发送消息,您需要使用带有nowait 选项的raiserror 命令。所以我写了一个存储过程
create procedure sp_test
as
begin
declare @i bigint, @m nvarchar(max)
select @i = 1
while @i < 10
begin
waitfor delay '00:00:01'
select @m = cast(@i as nvarchar(max))
raiserror(@m, 0, 0) with nowait
select @i = @i + 1
end
end
如果您尝试在 SSMS 中执行它,您将看到该消息出现在消息部分,而过程仍然有效。好的,我们收到了来自服务器的消息。现在我们需要在客户端处理它。
为此,我创建了一个这样的 SQLCommand
SqlCommand cmd = new SqlCommand("sp_Test");
cmd.Connection = new SqlConnection("Server=HOME;Database=Test;Trusted_Connection=True;");
现在来捕获我们使用 SqlConnection 对象的InfoMessage 的消息:
cmd.Connection.InfoMessage += Connection_InfoMessage;
static void Connection_InfoMessage(object sender, SqlInfoMessageEventArgs e)
{
Console.WriteLine(e.Message);
}
现在我们正在尝试显示消息
cmd.Connection.Open();
try
{
SqlDataReader r = cmd.ExecuteReader();
}
finally
{
cmd.Connection.Close();
}
成功:)
顺便说一句,您不能使用ExecuteNonQuery(),因为它会在执行结束时返回串联消息。
此外,您可能希望在后台模式下运行查询,这样它就不会锁定您的 winform 客户端。