2011-04-21 43 views
13

獲得SQL Server的「打印」值我有一個SP,打印結果爲SQL服務器,但我需要使用該值在C#需要在C#

PRINT更改爲SELECT目前不是一個選項。我試圖SqlCommand.ExecuteScalar(),但沒有奏效。

有誰知道是否有可能得到重定向到C#PRINT命令的SP價值?

例:

CREATE PROCEDURE doXYZ 
AS 
BEGIN 
    PRINT 'XYZ' 
END 

現在C#我需要得到的價值 'XYZ' ....任何想法?

+0

如何連接到數據庫?直接瞭解ADO.NET或某種ORM? – R0MANARMY 2011-04-21 21:14:29

+0

只是直升起來的ADO.NET。帶有connectionString的SqlConnection,然後是SQLcommand。 USING(SqlConnetion con = new SqlConnection(「Server = LOCALHOST; Database = XYZ; Trusted_Connection = Yes;」)) – 2011-04-21 21:18:41

+0

@Akram Shahda:非常好的編輯,使問題更具可讀性,如果我可以upvote我會=)。 – R0MANARMY 2011-04-22 04:34:08

回答

17

您可以使用SqlConnection.InfoMessage事件。

+0

完美。謝謝。 – 2011-04-21 22:04:22

+0

[查看我的回答](http://stackoverflow.com/a/22252379/224976)以及基於此答案的工作代碼 – 2014-03-07 14:12:27

12

可以使用SqlConnection.InfoMessage事件,像這樣:

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

namespace foo 
{ 
    class bar 
    { 
     static public void ExecuteStoredProc() 
     { 
      var connectionString = "Data Source=.;Integrated Security=True;Pooling=False;Initial Catalog=YourDatabaseName"; 
      using (var connection = new SqlConnection(connectionString)) 
      using (var command = new SqlCommand("dbo.YourStoredProcedure", connection)) 
      { 
       command.CommandType = CommandType.StoredProcedure; 
       command.Parameters.AddWithValue("@YourParameterName", "YourParameterValue"); 

       connection.Open(); 
       // wire up an event handler to the connection.InfoMessage event 
       connection.InfoMessage += connection_InfoMessage; 
       var result = command.ExecuteNonQuery();    
       connection.Close(); 
      } 
     } 

     static void connection_InfoMessage(object sender, SqlInfoMessageEventArgs e) 
     { 
      // this gets the print statements (maybe the error statements?) 
      var outputFromStoredProcedure = e.Message;    
     } 
    } 
}