简体   繁体   English

如何只删除表中的最高记录?

[英]How to delete only the top record from a table?

I'm just looking for simple code which deletes the top record from a table. 我只是在寻找简单的代码,该代码将从表中删除顶部的记录。

I've tried: 我试过了:

SqlCommand Delete = new SqlCommand("Command String", cn);
cn.Open();
Delete.CommandText = "DELETE TOP (1) queue.* FROM queue  ";
Delete.ExecuteNonQuery();
cn.Close();

But I get an error: 但是我得到一个错误:

Incorrect syntax near '*'. '*'附近的语法不正确。

TOP only seems to work with SELECT . TOP似乎只能与SELECT

You can do this: 你可以这样做:

DELETE TOP(1) FROM queue

However, this will just delete a random row (most likely the first row, but not necessarily). 但是,这只会删除随机行(很可能是第一行,但不一定)。 You probably want to do something more meaningful, such as this: 您可能想做一些更有意义的事情,例如:

DELETE FROM queue WHERE queueId IN (
     SELECT TOP 1 queueId FROM queue ORDER BY queueId
)

This is just an example. 这只是一个例子。 I don't know your table structure or fields, so you'll need to decide how to order it yourself. 我不知道您的表格结构或字段,因此您需要自行决定如何订购。 Keep in mind that issuing "DELETE TOP (1) from queue" will not necessarily delete the first row. 请记住,发出“从队列中删除顶部(1)”不一定会删除第一行。 What it does is it deletes the first row SQL server decided to serve you. 它所做的是删除决定为您服务的第一行SQL Server。 It may or may not be the first row in your table though. 它可能是也可能不是表中的第一行。

Your sql query for deleting the top record is wrong. 您用于删除顶部记录的sql查询是错误的。

Replace This: 替换为:

Delete.CommandText = "DELETE TOP (1) queue.* FROM queue  ";

With

Delete.CommandText = "DELETE TOP(1) FROM queue";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM