将多个生成的值插入表中

时间:2016-04-17 10:10:26

标签: c# sql asp.net

首先,我的问题非常复杂,而且我并不十分熟练地详细解释,所以我想提前说对不起。

好的,这就是事情。我执行此查询

string count = "SELECT Count(*) FROM Student WHERE IntakeID = 'MYVALUE'"

它将返回 10 的数量。所以我继续这段代码:

SqlCommand cmd = new SqlCommand(count, conn);
int temp = Convert.ToInt32(cmd.ExecuteScalar().ToString());
for (int x = 0; x < temp; x++)
{
     string query = "INSERT INTO Docket (DocketNo, StudentID) VALUES ('" + getUniqueKey() + "','(SELECT StudentID FROM Student WHERE IntakeID = 'MYVALUE')')
}

PS:getUniqueKey()是一种获取我生成的唯一键的方法。

这段代码在技术上是否正确?我想要的结果如下:

+-----------+-------------+
| DocketNo  | StudentID   |
+-----------+-------------+
| 18590394  | TP123456    |
| 09141563  | TP012457    |
| 58293495  | TP049185    |
+-----------+-------------+

如果你不清楚我的问题,我会尽力让它更清楚。很抱歉给您带来不便。

更新(答案): 在Paparazzi的帮助下(谢谢!)为他的代码,我修改并提出了我自己的解决方案。

string count = "SELECT StudentID FROM Student WHERE IntakeID = 'MYVALUE'"
SqlCommand cmd = new SqlCommand(count, conn);
string query = "INSERT INTO Docket (DocketNo, StudentID) VALUES ";
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
    if (rdr.HasRows)
    {
        var loop = true;
        while (loop)
        {
            loop = rdr.Read();
            if (!loop)
            {
             //When end of rows and no more data to be retrieve, it removes the last "," from  the query.
                char[] trimChar = { ',' };
                string newQuery = query.TrimEnd(trimChar);
                cmd.CommandText = newQuery;
            }
            else { 
                query += "('" + GetUniqueKey() + "','" + rdr.GetString(0) + "')";
                query += ",";
            }

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

所以实际上在循环SqlDataReader时,查询会在后台生成如下内容:

INSERT INTO  Docket(DocketNo, StudentID) VALUES ('1562456','TP028800'), ('1465446','TP028801'),..........('4939104','TP028810'),

注意会有一个&#34;,&#34;由于query += ",";,查询末尾的逗号。当SqlDataReader不再返回任何行时,它将执行if(!loop)语句以删除最后一个&#34;,&#34;来自查询的(逗号)。

如果您不清楚+=的含义,请参阅https://msdn.microsoft.com/en-us/library/sa7629ew.aspx

更新2: 如果您管理大量数据,@ Paparazzi已经提出了一种更有效且性能更好的方法。在他自己的帖子中查找他的代码。 :)

2 个答案:

答案 0 :(得分:2)

string count = "SELECT StudentID FROM Student WHERE IntakeID = 'MYVALUE'"
SqlCommand cmd = new SqlCommand(count, conn);
string query = "INSERT INTO Docket (DocketNo, StudentID) VALUES ";
conn.Open();
bool first = true;
using (SqlDataReader rdr = cmd.ExecuteReader())
{
    while (rdr.Read())
    {
        if (first)
          first = false;
        else 
           query += ", "
        query += "('" + getUniqueKey() + "', '" + rdr.GetString(0) + "')";  
    }
}
if (!first)
{
    cmd.CommandText = query + ";";
    cmd.ExecuteNonQuery();  
}
conn.Close();

StringBuilder比字符串上的+ =更快 多个值限制为1000(我认为),但比单个插入更有效率 因此,如果你可以获得超过1000,那么需要添加一个计数器并触发插入

string getID = "SELECT StudentID FROM Student WHERE IntakeID = 'MYVALUE'"
SqlCommand cmd = new SqlCommand(getID , conn);
string insert = "INSERT INTO Docket (DocketNo, StudentID) VALUES ";
Int32 count = 0;
StringBuiler sb = new StringBuiler();
conn.Open();    
using (SqlDataReader rdr = cmd.ExecuteReader())
{
    while (rdr.Read())
    {
        if (count == 0)
        { 
            sb.Clear();
            sb.AppendLine(insert);
        }
        else 
           sb.Append(", ")
        sb.Append("('" + getUniqueKey() + "', '" + rdr.GetString(0) + "')");
        count++;
        if(count > 800)
        {
            count = 0;
            cmd.CommandText = sb.ToString() + ";";
            cmd.ExecuteNonQuery(); 
            // most likely need a separate cmd here has a open reader 
            // will leave that as an exercise for you 
            // could even go asynch if you want to get faster
            // or you could just build up multiple inserts on sb 
        }  
    }
}
if (count > 0)
{
    cmd.CommandText = sb.ToString() + ";";
    cmd.ExecuteNonQuery();
}
conn.Close();

答案 1 :(得分:0)

SqlCommand cmd = new SqlCommand(count, conn);
int temp = Convert.ToInt32(cmd.ExecuteScalar().ToString());
for (int x = 0; x < temp; x++)
{
     string query += "INSERT INTO Docket (DocketNo, StudentID) VALUES ('" + getUniqueKey() + "','(SELECT StudentID FROM Student WHERE IntakeID = 'MYVALUE')');";


}
SqlCommand cmd = new SqlCommand(query, conn);
cmd.ExecuteQuery();