我想删除特定列
上具有最高值的行(我知道有答案,但由于某些原因,它们都不适合我)
我在visual studio c#中使用SQL
进行的所有编码MyDatabase:hours
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:'' Index'附近的语法不正确。如果 这是作为表提示的一部分,一个WITH关键字和 现在需要括号。请参阅SQL Server联机丛书 语法。
答案 0 :(得分:6)
索引是关键字,您需要使用[Index]
。
答案 1 :(得分:2)
尝试
delete from hours where Index = max(index);
答案 2 :(得分:1)
如“ajg”所述,第二个查询中的问题是使用保留关键字Index
使用方括号来转义关键字
更好的方法是使用CTE
;with cte as
(
select top (1) * from hours order by [Index] desc
)
delete from cte
答案 3 :(得分:1)
试试这个;
delete x
from dbo.[Hours] x
where exists(select 1 from dbo.[Hours] xx having MAX(xx.[Index])=x.[Index])
答案 4 :(得分:0)
在SQL Server中,您可以执行以下操作:
DELETE h
FROM hours h
WHERE h.Index = (select max(h2.Index) from hours h2) ;
如果您担心index
可能有重复项,请将delete
与top
一起使用。
答案 5 :(得分:0)
这应该有用;
DELETE FROM hours
WHERE Index = max(index);
答案 6 :(得分:0)
delete from hours where [Index] = (select max([Index]) from hours)
我猜你错过了括号。
答案 7 :(得分:0)
delete from tablename
where columnname =
( select dummytable.maxVal from
(select max(columnname) as maxVal from tablename)
dummytable
);