【问题标题】:Insert a value in a table from another table using a variable in C# , SQL Server使用 C#、SQL Server 中的变量从另一个表中插入一个表中的值
【发布时间】:2015-07-02 03:56:28
【问题描述】:

我必须在一个表中插入一些值,同时从另一个表中获取它们。这是我的代码:

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConString"].ConnectionString);

SqlCommand myCommand = new SqlCommand("SELECT Name FROM TableName WHERE Id = '" + Id + "'", con);

SqlDataReader rdr = myCommand.ExecuteReader();

if (dr.HasRows)
{
    while (rdr.Read())
    {
        // User exist - get email
        string Name = rdr["Name"].ToString();
    }
}

我的问题是如何将名称插入另一个表。

我不想为此使用文本框,必须将值作为变量插入到其他表中。我使用以下脚本插入数据。但错误消息是 Id not found。如果我遗漏了什么,请告诉我

SqlCommand cmd = new SqlCommand(@"insert into finalTable (AccountNumber) VALUES (@string)", con);

【问题讨论】:

  • @Eterm:他展示了他的尝试,并说出出了什么问题(尽管确切的错误信息会更有帮助)。
  • @EricJ。我的糟糕,预编辑我错过了第二个代码 sn-p。

标签: c# sql-server


【解决方案1】:

我使用以下脚本插入数据。但错误信息是 Id not found。

SqlCommand cmd = new SqlCommand(@"insert into finalTable (AccountNumber) VALUES
        (@string)", con);

您需要为表中的所有列指定一个值,除非某些列具有默认值。如果没有确切的错误消息很难判断,但听起来 Id 可能是主键列并且未设置为auto increment,因此您必须为 Id 提供一个值。由于您正在插入,因此它必须是表中尚未使用的值。根据您的需要,您可能希望将 finalTable 的 ID 更改为自动递增。

附带说明,您并没有处理实现 IDisposable 的东西(例如您的数据库连接)。 using 关键字是您的朋友。

【讨论】:

  • 糟糕,我已将 Name 插入 AccountNumber... 我认为这是我的输出的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多