如何使用插入语句从foreach中获取值

时间:2019-06-01 04:02:39

标签: c# sql-server winforms foreach

我是新手。我使用GetSelectedIndicesforeach来获取数组中的每个值。

此后,我为insert语句提供了这些值。如何从foreach中的insert语句获取query_TheLoai?我在网络表单上工作

var TheLoaiIds = lbxTheLoai.GetSelectedIndices();

foreach (var TheLoaiId in TheLoaiIds)
{
    string query_TheLoai = "SELECT @MaPhim = SCOPE_IDENTITY();INSERT INTO ChiTietTL VALUES ('" + TheLoaiId + "', @MaPhim)";
}

很抱歉尴尬

2 个答案:

答案 0 :(得分:0)

var TheLoaiIds = lbxTheLoai.GetSelectedIndices();
string CStr = "YourConnectionString";

string Query = "INSERT INTO ChiTietTL VALUES ('" + TheLoaiId + "', @MaPhim)";

using(var conn = new SqlConnection(CStr))
{
    foreach (var TheLoaiId in TheLoaiIds)
    {
        using(var cmd = new SqlCommand(Query, conn))
        {
             try
             {
                 cmd.Parameters.AddWithValue("@MaPhim", TheLoaiId);
                 cmd.ExecuteNonQuery();
             }
             catch (SqlException ex)
             {
                 MessageBox.Show(ex.ToString());
             }
         }
     }
}

答案 1 :(得分:0)

    var TheLoaiIds = lbxTheLoai.GetSelectedIndices();
    string CStr = "YourConnectionString";

    string Query = "SELECT @MaPhim = SCOPE_IDENTITY(); INSERT INTO ChiTietTL VALUES (@TheLoaiId, @MaPhim)";

    using(var conn = new SqlConnection(CStr))
    {
        foreach (var TheLoaiId in TheLoaiIds)
        {
            using(var cmd = new SqlCommand(Query, conn))
            {
                 try
                 {
                     cmd.Parameters.AddWithValue("@TheLoaiId", TheLoaiId);
                     cmd.ExecuteNonQuery();
                 }
                 catch (SqlException ex)
                 {
                     MessageBox.Show(ex.ToString());
                 }
             }
         }

}