2017-04-19 27 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并将其添加为第二个命令的值。

可能更好的做法是将两个查询重写为单个连接的查询。