2010-09-27 48 views
4

--Stored程序如何使用C#

ALTER PROCEDURE [dbo].[Test]    
@USERID varchar(25)    

AS    
BEGIN     
SET NOCOUNT ON      
IF NOT EXISTS Select * from Users where USERID = @USERID)   
    BEGIN       
     INSERT INTO Users (USERID,HOURS) Values(@USERID, 0);     
    END 

值傳遞到存儲過程我在SQL Server 2005中這個存儲過程,並希望從C#應用程序通過用戶ID。我怎樣才能做到這一點。非常感謝。

+0

可能重複[如何執行從C#程序中的存儲過程(http://stackoverflow.com/questions/1260952 /如何執行從c程序中存儲的程序) – 2010-09-27 17:29:30

+0

@John Fisher我們鼓勵可以通過Google搜索解答的問題。這樣當人們谷歌,像Stack Overflow這樣的權威來源出現時,而不是傳統的數百個論壇。 – 2010-09-27 17:31:38

+1

@George:這很有道理,但你不覺得MSDN足夠權威嗎? – 2010-09-27 17:39:46

回答

8

此主題在MSDN here中有詳細介紹。請參閱標題爲「使用與一個SqlCommand和存儲過程的參數」的一個很好的示例部分:

static void GetSalesByCategory(string connectionString, 
    string categoryName) 
{ 
    using (SqlConnection connection = new SqlConnection(connectionString)) 
    { 
     // Create the command and set its properties. 
     SqlCommand command = new SqlCommand(); 
     command.Connection = connection; 
     command.CommandText = "SalesByCategory"; 
     command.CommandType = CommandType.StoredProcedure; 

     // Add the input parameter and set its properties. 
     SqlParameter parameter = new SqlParameter(); 
     parameter.ParameterName = "@CategoryName"; 
     parameter.SqlDbType = SqlDbType.NVarChar; 
     parameter.Direction = ParameterDirection.Input; 
     parameter.Value = categoryName; 

     // Add the parameter to the Parameters collection. 
     command.Parameters.Add(parameter); 

     // Open the connection and execute the reader. 
     connection.Open(); 
     SqlDataReader reader = command.ExecuteReader(); 

     if (reader.HasRows) 
     { 
      while (reader.Read()) 
      { 
       Console.WriteLine("{0}: {1:C}", reader[0], reader[1]); 
      } 
     } 
     else 
     { 
      Console.WriteLine("No rows found."); 
     } 
     reader.Close(); 
    } 
} 
+0

堆棧溢出應該是我們保存代碼的地方;如果可能的話,不是第三方網站。此問題也是另一個問題的重複:http://stackoverflow.com/questions/1260952/how-to-execute-a-stored-procedure-from-c-program – 2010-09-27 17:30:10

+0

+1:即使我會更喜歡一個小例子。 :-) – Patrick 2010-09-27 17:30:23

+1

@George Stocker:但你添加的鏈接沒有任何可接受的答案,並且是關於*調用*存儲過程,而不是將參數傳遞給它們.. – Patrick 2010-09-27 17:32:18