2014-10-31 96 views
5

我對C#相當新,我試圖設置調用存儲過程在我的數據庫,它採用一個參數。C#存儲過程或函數期望不提供參數

我得到的錯誤「過程或函數‘SP_getName’需要參數‘@用戶名’,但未提供。」當我與參數提供它

我的存儲過程工作正常,我通過SQL運行管理工作室。

GO 

DECLARE @return_value int 

EXEC @return_value = [dbo].[SP_getName] 
    @username = 'bob101' 

SELECT 'Return Value' = @return_value 

GO 

但是,當我嘗試調用它的錯誤是我如何傳入參數,但我不能發現問題是什麼。

  //create a sql command object to hold the results of the query 
      SqlCommand cmd = new SqlCommand(); 

      //and a reader to process the results 
      SqlDataReader reader; 

      //Instantiate return string 
      string returnValue = null; 

      //execute the stored procedure to return the results 
      cmd.CommandText = "SP_getName"; 

      //set up the parameters for the stored procedure 
      cmd.Parameters.Add("@username", SqlDbType.NVarChar).Value = "bob101"; 

      cmd.CommandType = CommandType.Text; 
      cmd.Connection = this.Connection; 

      // then call the reader to process the results 
      reader = cmd.ExecuteReader(); 

任何幫助發現我的錯誤將不勝感激!

我也試着看這兩個職位,但我沒有任何運氣:

Stored procedure or function expects parameter which is not supplied

Procedure or function expects parameter, which was not supplied

謝謝!

+0

順便說一句,您不應該使用SP_作爲您的過程的前綴。這是保留給系統特效。如果MS在某些時候釋放具有相同名稱的proc,則不會再運行。老實說,你根本不應該使用前綴,他們沒有增加任何澄清。 – 2014-10-31 14:29:43

回答

13

您已經指出:

cmd.CommandType = CommandType.Text; 

因此你只需執行:

SP_getName 

其中一期工程,因爲它是該批次中的第一條語句,所以你可以打電話給沒有EXECUTE的程序,但你實際上並不包括參數。將其更改爲

cmd.CommandType = CommandType.StoredProcedure; 

也可以將您的CommandText更改爲:

EXECUTE SP_getName @username; 

作爲一個側面說明,你應該Avoid using the prefix 'sp_' for your stored procedures

和另外側面說明是使用using與IDisposable接口反對確保它們正確處置:

using (var connection = new SqlConnection("ConnectionString")) 
using (var cmd = new new SqlCommand("SP_getName", connection)) 
{ 
    cmd.CommandType = CommandType.StoredProcedure; 
    cmd.Parameters.Add("@username", SqlDbType.NVarChar).Value = "bob101"; 
    connection.Open(); 
    using (var reader = command.ExecuteReader()) 
    { 
     while (reader.Read()) 
     { 
      // Do something 
     } 
    } 
} 
+0

輝煌 - 感謝信息,工作得很好!在時間限制結束時將標記爲答案! :D – hlh3406 2014-10-31 12:02:40

+0

謝謝 - 將肯定會重命名我的存儲過程,並閱讀'使用'! – hlh3406 2014-10-31 12:09:08

+0

謝謝!有幫助 – iTSrAVIE 2017-02-09 12:37:32

0

嘗試刪除@

cmd.Parameters.Add("username", SqlDbType.NVarChar).Value = "bob101"; 
+0

嗨,不幸的是我仍然收到錯誤消息:「過程或函數'SP_getName'期望參數'@username',這是沒有提供。」 – hlh3406 2014-10-31 12:00:53

0

我ha d這個問題,但它不是關於命令類型的參數名稱。 我的問題是,當C#調用SP,對於沒有價值通行證「默認」的每個參數的關鍵字(我發現它在SQL事件探查器):

... @IsStop=0,@StopEndDate=default,@Satellite=0, ... 

在我的情況,我的參數類型是日期時間:

@StopEndDate datetime 

。我通過在存儲過程中爲此參數設置默認值來解決我的問題:

@StopEndDate datetime=null 
+0

(在我的答案的第一行中修正)參數名稱或命令類型 – Javad 2015-05-26 06:31:28

相關問題