我一直在尝试逐个删除几行,具体取决于一定的限制,我试图只删除最新的条目但是,我想出的解决方案是不断崩溃VSHOST,是否有更好的方法来实现同样的结果?
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("A apagar dados...");
bool check = true;
do
{
string connectionString;
var path = @"C:\Users\Administrator\Desktop\connstring.txt";
using (StreamReader sr = new StreamReader(path))
{
connectionString = sr.ReadLine();
}
var connection = new SqlConnection(connectionString);
string queryString = string.Empty;
using (SqlConnection deleteconnection = new SqlConnection(connectionString))
{
deleteconnection.Open();
connection.Open();
queryString = "DELETE FROM wgcdoccab WHERE numdoc = (SELECT MAX(numdoc) FROM WGCDOCCAB WHERE serie ='1' and tipodoc ='FSS' and contribuinte ='999999990' and datadoc = CONVERT(varchar(10),dateadd(dd, -1, getdate()),120))";
SqlCommand command = new SqlCommand(queryString, connection);
command.ExecuteNonQuery();
connection.Close();
}
using (SqlConnection deleteconnection = new SqlConnection(connectionString))
{
connection.Open();
deleteconnection.Open();
queryString = "SELECT max(numdoc) 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);
代码相对简单,在do-while结束后,它变成了无穷无尽的cicle,因为它总是会为numdoc返回一个NULL值,我似乎找不到绕过它的方法。 有什么建议吗?
答案 0 :(得分:3)
我不明白循环的必要性。你为什么不一次删除所有记录?
DELETE FROM wgcdoccab
WHERE
serie ='1' and
tipodoc ='FSS' and
contribuinte ='999999990' and
datadoc = CONVERT(varchar(10),dateadd(dd, -1, getdate()),120))";
如果你在循环中重复查询,它将删除所有这些记录,而不仅仅是最后的记录。
“最后的”究竟是什么意思?最后2个是最后100个?你必须给出“最后一个”的确切定义!
假设您要删除最后10个。您可以使用此查询(假设为T-SQL)来实现它:
DELETE FROM wgcdoccab
WHERE numdoc IN (
SELECT TOP 10 numdoc
FROM WGCDOCCAB
WHERE blahh blahh blahh
ODER BY numdoc DESC
)