SQL insert命令仅在循环中运行一次

时间:2013-03-13 21:27:53

标签: c# sql sql-server database visual-studio-2010

这是for循环,它将转到时间并将时间列设为true。这是第一次使用,但是当时间增加0.5时,它仍然是错误的。 for循环正在尝试MessageBox.Show(“”+ Time1 +“”);在for循环中。

for (double Time = time_began_5; Time < time_finished_5; Time = Time + 0.5)
        {
            string Time1 = Time.ToString("0.00");


            try
            {
                SqlConnection cn = new SqlConnection("Data Source=.\\SqlExpress;Initial Catalog=AllensCroft;Integrated Security=True;MultipleActiveResultSets=True;Application Name=EntityFramework;");

                cn.Open();
                SqlCommand Command = new SqlCommand("INSERT INTO Slots ([Date],[RoomID],[" + Time1 + "]) Values (@date,@room,1)", cn);
                Command.Parameters.AddWithValue("date", date);
                Command.Parameters.AddWithValue("room", rooms_combo.SelectedValue);

                Command.ExecuteNonQuery();


                try
                {
                    cn.Close();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                }

            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }

        }

这是数据库的样子,第一个真正的字段可以工作,但是当它循环到另一个时间时,它仍然是假的,我想这可能是因为如果我有一个具有该日期的现有行(日期)是主键),我无法更新该行,所以我可能需要一个IF存在行,更新,否则创建一个新行。

slots database

2 个答案:

答案 0 :(得分:3)

你正在插入。 在每个循环中,您插入一个新行,并仅为名称等于变量Time1的当前值的列设置值true。

没有其他列的值,它们可能默认为false。 (我想是位列)

如果您希望每列的默认值为true,那么最好更改数据库架构,为每个时间列添加默认值,否则您需要一长串参数

编辑:如果您的逻辑规定每个日期只需要一行,并且如果输入上述情况,则每次将列设置为true,则可以使用存储过程在数据库中移动此逻辑:

CREATE PROCEDURE InsertOrUpdateSlotFromCode(@dt smalldatetime, @roomID int)
AS
BEGIN
    DECLARE @cnt INT
    SELECT  @cnt = COUNT(*) from Slots WHERE [Date] = @dt
    if @cnt = 0 
        INSERT INTO Slots ([Date],[RoomID], <here all the time fields> VALUES (@dt, @roomID, 1, ....)
    else
        UPDATE Slots SET [09.00] = 1, ..... WHERE [Date] = @dt
    End 
END

然后你的代码调用sp

using(SqlConnection cn = new SqlConnection(.........))
{
    cn.Open();
    SqlCommand Command = new SqlCommand("InsertOrUpdateSlotFromCode", cn);
    Command.CommandType = CommandType.StoredProcedure;
    Command.Parameters.AddWithValue("date", date);
    Command.Parameters.AddWithValue("room", rooms_combo.SelectedValue);
    Command.ExecuteNonQuery();
}

当然现在你可以完全摆脱循环

答案 1 :(得分:3)

试试这个,你不必在每个循环中打开连接,首先创建你的sql语句循环遍历每个值,然后使用一个语句插入

private string CreateInsertStatement(double time_began_5, double time_finished_5)
{
   string sql = "INSERT INTO Slots ([Date],[RoomID],";
   string valuesql = " Values (@date,@room,";
   for (double Time = time_began_5; Time < time_finished_5; Time = Time + 0.5)
   {
    string Time1 = Time.ToString("0.00");
    sql+ = "[" + Time1 + "],";
    valuesql+ = "1,";
   }
   sql = sql.TrimEnd(',') + ") ";
   valuesql = valuesql.TrimEnd(',') + ") ";

   return sql + valuesql;
}

private string CreateUpdateStatement(double time_began_5, double time_finished_5)
{
    string sql = "UPDATE Slots SET ";
    string wheresql = " WHERE [Date] = @date AND [RoomID] = @room";
    for (double Time = time_began_5; Time < time_finished_5; Time = Time + 0.5)
    {
        string Time1 = Time.ToString("0.00");
        sql+ = "[" + Time1 + "] = 1,";        
    }
    sql = sql.TrimEnd(','); 
    return sql + wheresql;
}

然后在你的实际插入代码中:

try
{
    SqlConnection cn = new SqlConnection("Data Source=.\\SqlExpress;Initial Catalog=AllensCroft;Integrated Security=True;MultipleActiveResultSets=True;Application Name=EntityFramework;");

    cn.Open();
    SqlCommand Command;
    //check if row exists 
    Command = new SqlCommand("select count(*) from Slots WHERE [Date] = @date AND [RoomID] = @room", cn);
    Command.Parameters.AddWithValue("date", date);
    Command.Parameters.AddWithValue("room", rooms_combo.SelectedValue);

    var cnt = Command.ExecuteScalar();
    if(cnt!=null)
    {
        string sqlstr = ""
        if(Int32.Parse(cnt.ToString()) > 0)
        {
            sqlstr = CreateUpdateStatement(time_began_5,time_finished_5);
        }
        else if(Int32.Parse(cnt.ToString()) == 0)
        {
            sqlstr = CreateInsertStatement(time_began_5,time_finished_5);
        }
        Command = new SqlCommand(sqlstr, cn);
        Command.Parameters.AddWithValue("date", date);
        Command.Parameters.AddWithValue("room", rooms_combo.SelectedValue);
        Command.ExecuteNonQuery();
    }
    try
    {
        cn.Close();
    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }
}
catch (Exception e)
{
    Console.WriteLine(e.ToString());
}