【问题标题】:Insert multiple rows from another table and get the IDs of inserted rows in SQL Server 2000从另一个表中插入多行并在 SQL Server 2000 中获取插入行的 ID
【发布时间】:2015-07-15 18:01:15
【问题描述】:

我有表 A 和表 B,表 B 具有与 A 相同的列,并且只有一个额外的列 x ,我想从 A 插入一些行到 B ,然后我想更新这些最后插入的每一行为 x 列添加一个新值。

如何在 SQL Server 2000 中做到这一点?

现在我在 C# 代码中使用此查询,我从 A 中选择所有想要的行并将其保存在 DataTable

string Query = "Select * from A where ID = 5";

SqlDataAdapter dap = new SqlDataAdapter(Query, Conn);
dap.Fill(DataTablle1);

foreach (DataRow row in DataTablle1.Rows)
{
      string query2 = "Insert into B (col a , col b, col x) values ('" + row["col a"] + "','" + row["col b"] + "',3)";
}

这种方式需要很多插入语句,具体取决于表A中的行数,有没有什么方法可以用最少的插入语句来实现呢?

【问题讨论】:

  • 你想做什么......一旦返回第一个表,你可以循环遍历 DataTable1.Rows,就像你在尝试更新 DataTable1.Rows[Y]["X"] you will need to do this in a inner for loop.. there you will assign the values to the empty datatable rows string query2 时已经例外一样你想用这个做什么..你没有展示你想要做什么
  • 我正在循环遍历 DataTable 以将其值插入表 B。现在如果我在 DataTable 中有大约 100 行,表 B 中将有 100 个插入语句,我的问题:还有其他用最少的插入语句插入这 100 行的方法,例如插入选择语句?

标签: c# sql sql-server-2000


【解决方案1】:

你可以有一个带有文字 3 的插入选择语句:

INSERT INTO b ([col a] , [col b], [col x])
SELECT [col a], [col b], 3
FROM   a 
WHERE  id = 5

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-15
    • 2014-05-22
    相关资源
    最近更新 更多