簡體   English   中英

如何在存儲過程中使用OUTPUT參數

[英]How to use OUTPUT parameter in Stored Procedure

我是編寫存儲過程的新手。 所以我用輸出參數編寫了一個並想要訪問輸出值,熱點就可以了。

我的存儲過程:

ALTER PROCEDURE selQuery
    (
        @id int, @code varchar(50) OUTPUT
    )
AS
    SELECT RecItemCode = @code, RecUsername from Receipt where RecTransaction = @id
    RETURN @code

如果嘗試將“@ code = RecItemCode”設置為獲取錯誤:“為變量賦值的SELECT語句不得與Data Retrieval操作結合使用。”

我使用存儲過程:

con.Open();
cmd.Parameters.AddWithValue("@id", textBox1.Text);
SqlParameter code = new SqlParameter("@code", SqlDbType.Int);
code.Direction = ParameterDirection.Output;
cmd.Parameters.Add(code);
SqlDataReader sdr = cmd.ExecuteReader();
MessageBox.Show(cmd.Parameters["@code"].Value.ToString()); // getting error
con.Close();

錯誤:“對象引用未設置為對象的實例。” 我想得到輸出參數的值。 怎么做到的?

謝謝。

要使其正常工作,您需要解決幾個問題

  1. 這個名字是錯的,而不是@ouput它的@code
  2. 您需要將參數方向設置為Output。
  3. 不要使用AddWithValue因為它不應該只有你的Add值。
  4. 如果您沒有返回行,請使用ExecuteNonQuery

嘗試

SqlParameter output = new SqlParameter("@code", SqlDbType.Int);
output.Direction = ParameterDirection.Output;
cmd.Parameters.Add(output);
cmd.ExecuteNonQuery();
MessageBox.Show(output.Value.ToString());

SP中的SQL是錯誤的。 你可能想要

Select @code = RecItemCode from Receipt where RecTransaction = @id

在您的語句中,您沒有設置@code,您正在嘗試將其用於RecItemCode的值。 當您嘗試使用輸出參數時,這將解釋您的NullReferenceException ,因為永遠不會為其分配值,並且您將獲得默認的null。

另一個問題是你的SQL語句是否被重寫為

Select @code = RecItemCode, RecUsername from Receipt where RecTransaction = @id

它混合了變量賦值和數據檢索。 這突出了幾點。 如果除了數據的其他部分之外還需要驅動@code的數據,請忘記輸出參數並只選擇數據。

Select RecItemCode, RecUsername from Receipt where RecTransaction = @id

如果您只需要代碼,請使用我向您展示的第一個SQL語句。 關於實際需要輸出數據的隨機機會,請使用兩個不同的語句

Select @code = RecItemCode from Receipt where RecTransaction = @id
Select RecItemCode, RecUsername from Receipt where RecTransaction = @id

這應該將您的值賦給輸出參數以及連續返回兩列數據。 然而,這讓我覺得非常多余。

如果您按照我在頂部顯示的那樣編寫SP,只需調用cmd.ExecuteNonQuery(); 然后讀取輸出參數值。


您的SP和代碼的另一個問題。 在SP中,您已將@code聲明為varchar 在代碼中,將參數類型指定為Int 更改SP或代碼以使類型保持一致。


另請注意:如果您所做的只是返回一個值,那么還有另一種方法可以完全不涉及輸出參數。 你可以寫

 Select RecItemCode from Receipt where RecTransaction = @id

然后使用object obj = cmd.ExecuteScalar(); 要獲得結果,不需要SP或代碼中的輸出參數。

您需要使用ParameterDirection.Output枚舉將輸出參數定義為代碼中的輸出參數。 有很多這方面的例子,但這是MSDN上的一個。

SqlCommand yourCommand = new SqlCommand();
yourCommand.Connection = yourSqlConn;
yourCommand.Parameters.Add("@yourParam");
yourCommand.Parameters["@yourParam"].Direction = ParameterDirection.Output;

// execute your query successfully

int yourResult = yourCommand.Parameters["@yourParam"].Value;

您需要先關閉連接,然后才能使用輸出參數。 像這樣的東西

con.Close();
MessageBox.Show(cmd.Parameters["@code"].Value.ToString());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM