删除具有特定列的最高值的行

Delete a row with the highest value of a specific column

我想删除特定列上具有最高值的行

(我知道有答案,但 none 出于某种原因对我有用)

我在 visual studio c# 中使用 SQL

进行的所有编码

我的数据库:小时

Hours_Left | Hours_Spent | Time_Written | Mode | Time_Start | Time_End | Index
==============================================================================
aa         | bb          | cc           | dd   | ee         | ff       | 3
gg         | hh          | ii           | jj   | kk         | ll       | 4
mm         | nn          | oo           | pp   | qq         | rr       | 5
ss         | tt          | uu           | vv   | ww         | xx       | 6

[Hours_Left]   VARCHAR (MAX) NULL,
[Hours_Spent]  VARCHAR (MAX) NULL,
[Time_Written] VARCHAR (MAX) NULL,
[Mode]         VARCHAR (MAX) NULL,
[Time_Start]   VARCHAR (MAX) NULL,
[Time_End]     VARCHAR (MAX) NULL,
[Index]        INT           IDENTITY (1, 1) NOT NULL

我的代码:

if (con.State != ConnectionState.Open)
        {
            con.Close();
            con.Open();
        }
        SqlCommand cmd = con.CreateCommand();
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = @"DELETE FROM hours WHERE Index = select max(Index) from hours limit 1";
        cmd.ExecuteNonQuery();
        con.Close();
        Display_Data();

commandText

时也不工作
@"DELETE TOP(1) FROM hours
  WHERE Index in 
  (SELECT TOP(1) Index FROM hours
  ORDER BY Index DESC);";

我想删除最高索引的整行 - 即删除索引为 6 的行,它是最高索引

错误发生在:

cmd.ExecuteNonQuery();

错误是:

System.Data.SqlClient.SqlException: 'Incorrect syntax near 'Index'. If this is intended as a part of a table hint, A WITH keyword and parenthesis are now required. See SQL Server Books Online for proper syntax.

在SQL服务器中,您可以:

DELETE h
    FROM hours h
    WHERE h.Index = (select max(h2.Index) from hours h2) ;

如果您担心 index 可能重复,请使用 deletetop

尝试

 delete from hours where Index = max(index);

如 "ajg" 所述,第二个查询中的问题是使用保留关键字 Index 使用方括号转义关键字

更好的方法是使用 CTE

;with cte as
(
select top (1) * from hours order by [Index] desc
)
delete from cte

index是关键词,需要使用[Index].

试试这个;

delete x
from dbo.[Hours] x
where exists(select 1 from dbo.[Hours] xx having MAX(xx.[Index])=x.[Index])
  delete from hours where [Index] = (select max([Index]) from hours)

我猜你漏了括号。

 delete from tablename 
 where columnname = 
 ( select dummytable.maxVal from 
    (select max(columnname) as maxVal from tablename) 
   dummytable
 );