2012-12-09 32 views
0

我有一個返回列值的SQL存儲過程(SQL數據類型:nchar(1))。存儲過程運行並在傳遞參數時返回所需的值。基於這個返回值,我想轉移程序流程。爲此,我需要讀取ASP.NET C#變量中返回的值,但我不確定該如何執行此操作。如何存儲返回行或列值到ASP.NET C#變量的SQL存儲過程結果?

create procedure sproc_Type 
     @name as nchar(10) 
AS  
SELECT Type FROM Table WHERE Name = @name 

我想在cs文件讀取Type價值,並希望將其保存以備後用。

回答

0
   SqlConnection conn = null; 
      SqlDataReader rdr = null; 
      conn = new 
       SqlConnection("Server=(local);DataBase=Northwind;Integrated Security=SSPI"); 
      conn.Open(); 

      // 1. create a command object identifying 
      //  the stored procedure 
      SqlCommand cmd = new SqlCommand(
       "Stored_PROCEDURE_NAME", conn); 

      // 2. set the command object so it knows 
      // to execute a stored procedure 
      cmd.CommandType = CommandType.StoredProcedure; 

      // 3. add parameter to command, which 
      // will be passed to the stored procedure 
      cmd.Parameters.Add(
       new SqlParameter("@PARAMETER_NAME", PARAMETER_VALUE)); 

      // execute the command 
      rdr = cmd.ExecuteReader(); 

      // iterate through results, printing each to console 
      while (rdr.Read()) 
      { 
       var result = rdr["COLUMN_NAME"].ToString(); 
      } 
+1

使用'using'並關閉打開的連接... – Aristos

+0

感謝您的答覆傢伙,BYT我專門找我有寫的內部,而循環 – user1889838

+0

VAR的結果= RDR [代碼」 COLUMN_NAME「]的ToString(); – Moiz

0
string connectionString = "(your connection string here)"; 
string commandText = "usp_YourStoredProc"; 

using (SqlConnection conn = new SqlConnection(connectionString)) 
{ 
SqlCommand cmd = new SqlCommand(commandText, conn); 
cmd.CommandType = CommandType.StoredProcedure; 
cmd.CommandTimeout = 600; 

conn.Open(); 
SqlDataReader dr = cmd.ExecuteReader(); 
while(dr.Read()) 
{ 
// your code to fetch here. 
} 
conn.Close(); 

}