如何在asp.net中执行多个sql命令

时间:2014-05-29 08:53:18

标签: c# asp.net sql

我有:

 string commandText = @"SELECT cn.companyName from Companies cn 
               INNER JOIN KeyProcesses uc ON uc.companyId = cn.companyId  
               WHERE uc.description like '%" + ProcessInputClause + "%';";

 string addr = @"SELECT address FROM Companies where companyName = @companyName";

执行我尝试过:

SqlCommand sqlCmd = new SqlCommand();
sqlCmd.CommandText = commandText;
sqlCmd.Parameters.Clear();
string connectionString = ConfigurationSettings.AppSettings["connectionString"];
using (SqlConnection connection = new SqlConnection(connectionString))
{
   SqlCommand command = new SqlCommand(commandText, connection);
   try
   {
       connection.Open();
       sqlCmd = new SqlCommand(sqlCmd.CommandText, connection);
       SqlDataReader sqlReader = sqlCmd.ExecuteReader();
       DataTable dt = new DataTable();

       sqlReader.Read();
       dt.Load(sqlReader);
       Label1.Text = dt.Rows[0][0].ToString();
       sqlCmd.CommandText = addr;
       SqlCmd.Parameters.AddWithValue("@companyName", "namehere");
       SqlDataReader addressReader = sqlCmd.ExecuteReader();
       addressReader.Read();
       Label1.Text = Label1.Text + addressReader["address"].ToString() + addressReader.GetValue(1).ToString() + addressReader.GetString(0) + addressReader.GetString(1);

我只能获得第一个要执行的sql,并将companyName获取为Label1.text。但看起来第二个executeReade()没有给我任何结果,虽然我单独尝试了查询!我也尝试了combine命令文本并使用nextresult但没有运气。你能帮我解决一下如何成功执行这两个命令吗? Ps:添加了调用addressReader.Read();我忘了复制这个,试过这个但没有结果!

3 个答案:

答案 0 :(得分:6)

首先要做的是参数化第一个查询; p

之后,需要更改的所有内容是实际使用第二个阅读器:

using(var addressReader = sqlCmd.ExecuteReader()) {
    if(addressReader.Read()) {
        Label1.Text = Label1.Text + addressReader["address"].ToString()
         + addressReader.GetValue(1).ToString() + addressReader.GetString(0)
         + addressReader.GetString(1);
    }
}

编辑:删除它,因为它不适用,因为这两个查询是分层的

<击> 你可以在单个sql操作(NextResult()等)中执行两个选择,但我不确定dt.Load是否可以正常运行;不过值得一试:

sqlCommand.CommandText = @"
    SELECT cn.companyName from Companies cn 
    INNER JOIN KeyProcesses uc ON uc.companyId = cn.companyId  
    WHERE uc.description like '%' + @description+ '%';

    SELECT address FROM Companies where companyName = @companyName;";

sqlCommand.Parameters.AddWithValue("description", ProcessInputClause);
sqlCommand.Parameters.AddWithValue("companyName", "namehere");
using(var reader = sqlCommand.ExecuteReader()) {
    dt.Load(reader);
    if(reader.NextResult() && reader.Read()) {
        Label1.Text = Label1.Text + reader["address"].ToString()
         + reader.GetValue(1).ToString() + reader.GetString(0)
         + reader.GetString(1);
    }
}

<击>

由于查询之间存在依赖关系,并且地址是公司记录的一部分,我只会这样做:

@"SELECT cn.companyName, cn.Address from Companies cn 
           INNER JOIN KeyProcesses uc ON uc.companyId = cn.companyId  
           WHERE uc.description like '%" + @description + "%';";

获取两个值的单个查询。您可以使用现有的dt.Load来访问它,从第一列获取名称,从第二列获取地址 - 但坦率地说,我是&#34; dapper&#34;的忠实粉丝,所以我&# 39; d这样做:

class Company {
    public string CompanyName {get;set;}
    public string Address {get;set;}
}
...
var rows = conn.Query<Company>(
    @"SELECT cn.companyName, cn.Address from Companies cn 
      INNER JOIN KeyProcesses uc ON uc.companyId = cn.companyId  
      WHERE uc.description like '%" + @description + "%';",
    new { description = ProcessInputClause }).ToList();

然后迭代rows

foreach(var row in rows) {
    string name = row.CompanyName;
    string address = row.Address;
    // ...
}

或者,如果您不想申报类型:

var rows = conn.Query(
    @"SELECT cn.companyName, cn.Address from Companies cn 
      INNER JOIN KeyProcesses uc ON uc.companyId = cn.companyId  
      WHERE uc.description like '%" + @description + "%';",
    new { description = ProcessInputClause }).ToList();
foreach(var row in rows) {
    string name = row.companyName; // yes, this works
    string address = row.Address;
    // ...
}

在涉及多个表的场景中,您可以使用表变量作为连接的基础:

declare @ids table (CompanyId int not null)
insert @ids (CompanyId)
select companyId from Companies cn
INNER JOIN KeyProcesses uc ON uc.companyId = cn.companyId  
WHERE uc.description like '%" + @description + "%';

select cn.CompanyName, cn.Address
from @ids #i
inner join Companies cn on cn.CompanyId = #i.CompanyId

select /* other stuff */
from @ids #i
inner join /* other tables */

select /* yet more other stuff */
from @ids #i
inner join /* yet more other tables */

答案 1 :(得分:0)

您可以将两个命令放在字符串数组上,并在命令中执行foreach语句命令。

像这样:

string command1 = @"SELECT cn.companyName from Companies cn 
               INNER JOIN KeyProcesses uc ON uc.companyId = cn.companyId  
               WHERE uc.description like '%" + ProcessInputClause + "%';";
string command2 = @"SELECT address FROM Companies where companyName = @companyName";

string[] commands  = new string[2];
        commands.SetValue(command1 , 0);
        commands.SetValue(command2 , 1);

然后:

Foreach(string command in commands)
{
    SqlCommand c= new SqlCommand(command , connection);
    //do the rest
}

答案 2 :(得分:0)

使用DataSet而不是Datatable

DataSet ds = new DataSet();

SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString);


SqlDataAdapter da = new SqlDataAdapter(qry, connection);

da.Fill(ds);