使用数据适配器填充数据集

时间:2014-05-14 06:31:56

标签: c# sql-server

我的代码如下。

SqlCommand command = new SqlCommand();
command.Parameters.AddWithValue("@AccountId", accountNumberLong);
StringBuilder sql = new StringBuilder();
sql.AppendLine("SELECT * FROM T_POSTAGE_DISCOUNT");
sqlQuery = sql.ToString();

using (SqlConnection connection = new SqlConnection(connectionString))
{
    connection.Open();
    command.Connection = connection;
    command.CommandType = CommandType.Text;
    command.CommandText = sqlQuery;
    SqlDataAdapter dataAdapter = new SqlDataAdapter(command);
    dataAdapter.Fill(dsDiscounts, "Discounts");
}

到这里工作正常。我想在此数据集中添加另一个表。然后我确实喜欢这个。

command.Parameters.AddWithValue("@DISCOUNT_LEVEL_NBR",discountLevelNBR);
sql.AppendLine("select * from T_CONTRACT WHERE DISCOUNT_LEVEL_NBR=@DISCOUNT_LEVEL_NBR");
sqlQuery = sql.ToString();
using (SqlConnection connection = new SqlConnection(connectionString))
{

    connection.Open();
    command.Connection = connection;
    command.CommandType = CommandType.Text;
    command.CommandText = sqlQuery;
    SqlDataAdapter dataAdapter = new SqlDataAdapter(command);
    dataAdapter.Fill(dsDiscounts,"CONTRACT");

}

再次添加所有表格。我想将onlt合约表添加到现有数据集中 我怎么能这样做?(c#)

2 个答案:

答案 0 :(得分:1)

试试这个。

DataTable myTable = new DataTable("MyTable");
adapter.Fill(myTable);
ds.Tables.Add(myTable);

答案 1 :(得分:0)

问题是由于您在字符串sql上追加了两次而已, 当您写sql.AppendLine("...");时 字符串 sql = "select * from T_CONTRACT WHERE DISCOUNT_LEVEL_NBR=@DISCOUNT_LEVEL_NBR"

然后在另一行中,再次向sql字符串添加命令,使其变为
sql = "select * from T_CONTRACT WHERE DISCOUNT_LEVEL_NBR=@DISCOUNT_LEVEL_NBR" "select * from T_CONTRACT WHERE DISCOUNT_LEVEL_NBR=@DISCOUNT_LEVEL_NBR"
因此很清楚为什么再次带来所有表格。
因此,最好使用两个字符串sql1,sql2。