使用条件更新表上的行

时间:2015-07-21 19:19:21

标签: c# mysql

我正在尝试删除所有行,从表的底部开始使用条件,但是当满足条件时,我希望它停止更新表并保持其余部分不变。例如,如果表中的最后一个条目满足它,则将其删除,如果后面的条目不符合条件,则停止,然后退出循环。 这是我得到的代码,但它删除了所有行:

 private void button1_Click(object sender, EventArgs e)
    {
        MessageBox.Show("A atualizar dados");
        bool check = true;
        do
        {
            string connectionString = @"Data Source=.\wintouch;Initial Catalog=bbl;User ID=sa;Password=Pa$$w0rd";
            string queryString = string.Empty;
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.Open();

                queryString = "DELETE FROM wgcdoccab 
                WHERE serie ='1' AND tipodoc ='FSS' 
                AND contribuinte ='999999990' 
                and datadoc = CONVERT(varchar(10),(dateadd(dd, -2, getdate())),120)"

                SqlCommand command = new SqlCommand(queryString, connection);
                //command.Connection.Open();
                command.ExecuteNonQuery();

            }
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.Open();

                queryString = "SELECT * FROM wgcdoccab 
                WHERE serie !='1' and tipodoc !='FSS'
                and contribuinte !='999999990' 
                and  datadoc != CONVERT(varchar(10),(dateadd(dd, -1, getdate())),120) ";

                using (SqlCommand command = new SqlCommand(queryString, connection))
                using (SqlDataReader reader = command.ExecuteReader())
                {
                    if (reader.HasRows)
                    {

                        check = true;

                    }
                    else
                    {
                        check = false;
                        MessageBox.Show("Dados Apagados com sucesso");
                    }
                    command.Connection.Close();
                }
            }
        }
        while (check);

1 个答案:

答案 0 :(得分:0)

尝试类似这样的例子:

DELETE
FROM tableName
WHERE ID > 
(
    SELECT MAX(ID)
    FROM tableName
    WHERE condition = false
)

例如,如果要删除值为4:

DELETE
FROM tableName
WHERE ID > 
(
    SELECT MAX(ID)
    FROM tableName
    WHERE tableName.Value = 4
)

如果表格行为:

|ID|Value|
| 1|    7|
| 2|    4|

然后子选择将为2并且不会删除任何行。但是,如果行是:

|ID|Value|
| 1|    7|
| 2|    4|
| 3|    9|
| 4|    1|

然后子选择仍将返回ID 2,最后2行将被删除。