![](/img/trans.png)
[英]In SQL Server delete duplicates of date leaving only one record as per date
[英]Delete only one record on SQL Server
假定在SQL Server上有一個表EMPLOYEE
,其列ID (int), Name (nvarchar), Surname(nvarchar)
。
這就是您所知道的。 您無法在表格內看到數據。
您被命令僅刪除名稱為“ Alice”的一條記錄。
您將如何編寫適當的查詢?
DELETE TOP (1)
FROM EMPLOYEE
WHERE Name='Alice'
DELETE TOP (1) FROM EMPLOYEE WHERE Name = 'Alice'
在SQL Server中:
DELETE TOP 1 FROM EMPLOYEE WHERE Name = 'Alice'
此處建議的所有答案基本上都是相似的,就您介紹問題而言,它們都是最佳的。
但這將迫使您的代碼刪除Name ='Alice'的第一條記錄。 但是,如果您需要一點額外的權力來選擇要刪除的“愛麗絲”(如果表中有多個)。 但是ID必須是Primary Key
或Unique
SELECT FROM EMPLOYEE ID, Surname WHERE Name = 'Alice'
這將顯示結果,然后您可以獲取要刪除的目標記錄的ID並將其放在以下查詢中(假設您要刪除的記錄的ID為56)
DELETE FROM EMPLOYEE WHERE ID = 56
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
*/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.