我正在尝试删除表上的最新条目,但我使用的SQL查询根本就不删除任何内容。我使用断点并多次读取代码,无法找到任何错误,有人能告诉我我做错了吗?
private void button1_Click(object sender, EventArgs e)
{
string connectionString;
var path = @"C:\Users\Administrator\Desktop\connstring.txt";
using (StreamReader sr = new StreamReader(path))
{
connectionString = sr.ReadLine();
}
var connection = new SqlConnection(connectionString);
MessageBox.Show("Um grupo de trabalhadores, está agora a apagar os seus dados, aguarde.");
string queryString = string.Empty;
using (connection)
{
connection.Open();
queryString = "DELETE FROM wgcdoccab WHERE numdoc IN (SELECT TOP 100 numdoc FROM WGCDOCCAB WHERE serie ='1' and tipodoc ='FSS' and contribuinte ='999999990' and datadoc = CONVERT(varchar(10),dateadd(dd, -1, getdate()),120) ORDER BY numdoc DESC)";
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Close();
}
MessageBox.Show("Apesar de cansados e sujos os trabalhadores mandam avisar que foi tudo apagado!");
答案 0 :(得分:2)
您需要做的第一件事是在command
上调用ExecuteNonQuery
:
int deletionCount = command.ExexuteNonQuery();
Console.WriteLine("Deleted {0} items", deletionCount);
接下来,您需要确保命令本身已关闭,而不是其连接。连接由using
语句关闭,因此您无需担心。
更改后代码应如下所示:
using (var connection = new SqlConnection(connectionString)) {
connection.Open();
MessageBox.Show("Um grupo de trabalhadores, está agora a apagar os seus dados, aguarde.");
string queryString = string.Empty;
queryString = "DELETE FROM wgcdoccab WHERE numdoc IN (SELECT TOP 100 numdoc FROM WGCDOCCAB WHERE serie ='1' and tipodoc ='FSS' and contribuinte ='999999990' and datadoc = CONVERT(varchar(10),dateadd(dd, -1, getdate()),120) ORDER BY numdoc DESC)";
using (SqlCommand command = new SqlCommand(queryString, connection)) {
int deletionCount = command.ExexuteNonQuery();
MessageBox.Show("Deleted "+deletionCount+" items");
}
}
如果表包含100个匹配的记录,则此代码应显示Deleted 100 items
,如果表中的匹配记录少于100个,则显示已删除记录的实际数量。