c# 獲取sqlserver 運行腳本的print消息的方法分享

轉自:http://www.maomao365.com/?p=6923 web

摘要:
在sql腳本的編寫中,咱們常用sql腳本print消息,做爲輸出測試,
經過獲取print消息,咱們能夠快速獲取程序中的錯誤信息,下文講述經過 SqlInfoMessageEventHandler 獲取print信息,以下所示:
實驗環境:sqlserver 2008 R2 sql


 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;


using System.Data; 
using System.Data.SqlClient;
namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{


webCrm.SAG tmp = new webCrm.SAG();

protected void Page_Load(object sender, EventArgs e)
{
/*獲取 sql print的消息信息*/
string connectionString = "data source=***********;initial catalog=boss;user id=sa;password=erp;";

using (SqlConnection sqlcon = new SqlConnection(connectionString))
{
sqlcon.Open();
sqlcon.InfoMessage += new SqlInfoMessageEventHandler(OnReceivingInfoMessage);
/* 查詢某個表上的索引碎片的詳細信息 */
SqlCommand cmd = new SqlCommand("print '輸出消息1'; set statistics io on ;select * from [ierror] ; print '輸出sql消息完畢'", sqlcon);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
Console.Read();


}

 

private void OnReceivingInfoMessage(object sender, SqlInfoMessageEventArgs e)
{ 
Response.Write("輸出sql消息:" + e.Message.ToString());
}

 


}
}

 

----------------------輸出-------------------------------------------------------------------------
輸出sql消息:輸出消息1
表 'IError'。掃描計數 1,邏輯讀取 1 次,物理讀取 0 次,預讀 0 次,lob 邏輯讀取 0 次,lob 物理讀取 0 次,lob 預讀 0 次。
輸出sql消息完畢 c#

相關文章
相關標籤/搜索