假设在SQL Server上有一个包含EMPLOYEE
列的表ID (int), Name (nvarchar), Surname(nvarchar)
。
这就是你所知道的全部。您无法在表格中看到数据。
您被命令只删除一个名为“Alice”的记录。
您如何撰写适当的查询?
答案 0 :(得分:8)
DELETE TOP (1)
FROM EMPLOYEE
WHERE Name='Alice'
答案 1 :(得分:5)
DELETE TOP (1) FROM EMPLOYEE WHERE Name = 'Alice'
答案 2 :(得分:3)
在SQL Server中:
DELETE TOP 1 FROM EMPLOYEE WHERE Name = 'Alice'
答案 3 :(得分:1)
这里建议的所有答案都是相似的,只要您介绍问题,所有这些答案都是最佳的。
但这会强制您的代码删除Name ='Alice'的第一条记录。但是如果你需要有一点额外的力量来选择哪个'Alice'要删除,如果你的表中有多个。但当然,ID必须是Primary Key
或Unique
SELECT FROM EMPLOYEE ID, Surname WHERE Name = 'Alice'
这将显示结果,然后您可以将要删除的目标记录的ID放入以下查询(假设您要删除的记录的ID为56)
DELETE FROM EMPLOYEE WHERE ID = 56
答案 4 :(得分:0)
declare @Holder table ( EmployeeKey int , Name varchar(24) , Surname varchar(24) )
Insert into @Holder ( EmployeeKey , Name , Surname )
select 201 , 'Alice' , 'Smith'
union all select 102 , 'Mary' , 'Smith'
union all select 203 , 'Alice' , 'Henderson'
union all select 104 , 'John' , 'Smith'
union all select 105 , 'Paul' , 'Johnson'
union all select 206 , 'Alice' , 'Jones'
Delete @Holder
/* Select * ............. while debugging, you can remove the 'Delete @Holder' and put in a 'Select *' to see the results (of what ~will be deleted) */
From
@Holder h
join
(select top 1 EmployeeKey from @Holder innerH where Name = 'Alice' /* order by EmployeeKey DESC */ ) as derived1
on h.EmployeeKey = derived1.EmployeeKey
select * from @Holder order by Name , EmployeeKey
/*
order by EmployeeKey DESC is optional, aka, if you want to "prefer" which one gets popped for delete, you can tweak it as needed
*/