2017-04-19 26 views
0

我有一個SQL命令我運行,但工作很好,但對於AddWithValue參數之一我想使用另一個SQL命令來獲取該值...這是我有,但我想要使​​用的cmd2不起作用。它甚至有可能獲得數據的方式在理論上它是有道理的,但它似乎並沒有工作..使用SQL命令作爲參數值在C#

cmd2 = new SqlCommand("SELECT acctNum FROM custInfo WHERE customerName = @customerName", cn); 
    cmd2.Parameters.AddWithValue("@customerName", customerDropDown.Text); 

    cmd = new SqlCommand("UPDATE custInfo SET ctGal = (ctGal - (@contractGallons)) WHERE acctNum = @acctNum", cn); 

    cmd.Parameters.AddWithValue("@contractGallons", gallonsTextBox.Text)   
    cmd.Parameters.AddWithValue("@acctNum", cmd2); 
+5

'update ... where acctNum in(select c.acctNum from custInfo c ...)'? –

+0

您不執行'cmd2'來獲取'acctNum'值。但@DmitryBychenko會更好地工作,因爲它只有1次調用數據庫。 –

+2

甚至更​​簡單 - 'UPDATE custInfo SET ctGal =(ctGal - (@contractGallons))WHERE customerName = @ customerName' - 如果您已擁有'@ customerName',則實際上不需要'acctNum' ... –

回答

0

你必須使用cmd2.ExecuteReader()得到ACCTNUM例如

你可以試試下面的代碼

using (SqlDataReader reader = cmd2.ExecuteReader()) 
{ 
    if (reader.Read()) 
    { 
    cmd = new SqlCommand(@"UPDATE custInfo SET ctGal = (ctGal - 
    (@contractGallons)) WHERE acctNum = @acctNum", cn); 

    cmd.Parameters.AddWithValue("@contractGallons", gallonsTextBox.Text)   
    cmd.Parameters.AddWithValue("@acctNum", reader["acctNum"]); 

    } 
} 

希望這將有助於..

+0

這工作完美!我知道我並不太遙遠! – ksuProgrammer

2

我建議這兩個查詢合併爲一個:

//DONE: let keep query readable 
string sql = 
    @"UPDATE custInfo 
     SET ctGal = (ctGal - (@contractGallons)) 
    WHERE acctNum IN (SELECT c.acctNum 
         FROM custInfo c 
         WHERE c.customerName = @customerName)"; 

//DONE: wrap IDisposable into using 
using (var cmd = new SqlCommand(sql, cn)) { 
    //TODO: get rid of AddWithValue, but specify the actual fields' types 
    cmd.Parameters.AddWithValue("@contractGallons", gallonsTextBox.Text); 
    cmd.Parameters.AddWithValue("@customerName", customerDropDown.Text); 

    cmd.ExecuteNonQuery(); 
} 
1

你有兩個選擇,如果你想要走這條路:

  1. 將二者結合起來查詢時,實例化第二的SqlCommand。這將需要向第二個命令添加第二個參數。
  2. 或運行第一個命令。獲取結果acctNum並將其添加爲第二個命令的值。

可能更好的做法是將兩個查詢重寫爲單個連接的查詢。