【问题标题】:Asp.net how to get 1 word of a row from an table in a database to another tableAsp.net如何从数据库中的一个表中获取一行的1个单词到另一个表
【发布时间】:2017-03-09 15:27:14
【问题描述】:

我的问题就像标题一样:

如何使用两个表中都存在的用户名从数据库中的一个表中获取一行的 1 个单词到另一个表。

这是我尝试过的

var word = db.QueryValue("SELECT wordlist FROM tableold WHERE username IN(SELECT username FROM tablenew)");
var insertCommand = "INSERT INTO tablenew (wordlist) VALUE(word)";
db.execute(insertCommand, word);

当然以 db 作为我的数据库。

这里的问题是这里不能插入“word”,因为那是不允许的。

我的问题:有没有办法做到这一点?帮助将不胜感激!

【问题讨论】:

  • 请添加示例数据。

标签: c# sql asp.net database


【解决方案1】:

只需使用insert . . . select:

INSERT INTO tablenew (wordlist)
    SELECT wordlist
    FROM tableold 
    WHERE username IN(SELECT username FROM tablenew);

【讨论】:

  • 我已经做到了,只是 sql 命令不会在 asp.net 中使用 c#code,这就是为什么我尝试了上面的内容。
【解决方案2】:

不妨试试这种方法:

DataTable words = new DataTable();
string word = string.Empty;

using (SqlConnection conn = new SqlConnection("yourConnectionString"))
{
     SqlCommand cmd = new SqlCommand();
     cmd.CommandType = System.Data.CommandType.Text;
     cmd.Connection = conn;
     cmd.CommandText = @"SELECT wordlist FROM tableold WHERE username IN(SELECT username FROM tablenew)";

     SqlDataAdapter adap = new SqlDataAdapter();
     adap.SelectCommand = cmd;

     adap.Fill(words);
}

if (words != null && words.Rows.Count > 0)
{
     word = words.Rows[0].Field<string>("wordlist"); // for example
     using (SqlConnection conn = new SqlConnection("yourConnectionString"))
     {
          SqlCommand cmd = new SqlCommand();
          cmd.CommandType = System.Data.CommandType.Text;
          cmd.Connection = conn;
          cmd.Parameters.AddWithValue("@word", word);
          cmd.CommandText = @"INSERT INTO tablenew(wordlist) VALUE(@word)";

          conn.Open();
          cmd.ExecuteNonQuery();
          conn.Close();
      }
}

【讨论】:

    【解决方案3】:

    简单的 awnser 是将 @0 放在插入查询中的单词位置

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多