2011-09-17 107 views
3

我有一個帶有列的表(registration_no varchar(9))。下面是一個示例:刪除沒有前導零的行

id registration no 
1 42400065 
2 483877668 
3 019000702 
4 837478848 
5 464657588 
6 19000702 
7 042400065 

請注意登記號碼的像(042400065)和(42400065),他們幾乎是相同的,所不同的只是前導零。

我要選擇具有與上述相同的情況下,所有的註冊號,並刪除那些不帶前導零,即(42400065)

PLS,也注意到,在我刪除那些沒有前導零(42400065) ,我需要確保有一個等同於前導零(042400065)

回答

2
declare @T table 
(
    id int, 
    [registration no] varchar(9) 
) 

insert into @T values 
(1, '42400065'), 
(2, '483877668'), 
(3, '019000702'), 
(4, '837478848'), 
(5, '464657588'), 
(6, '19000702'), 
(7, '042400065') 

;with C as 
(
    select row_number() over(partition by cast([registration no] as int) 
          order by [registration no]) as rn 
    from @T 
) 
delete from C 
where rn > 1 
+0

+1。正在考慮轉換爲'int',但在我看到您的解決方案時還不確定如何使用它。而且這對我來說似乎是最佳的,非常好! –

0
create table temp id int; 
insert into temp select id from your_table a where left (registration_no,) = '0' and 
    exists select id from your_table 
       where a.registration_no = concat ('0', registration_no) 

delete from your_table where id in (select id from temp); 

drop table temp; 
0

我想你可以用一個DELETE語句來做到這一點。 JOIN確保只有重複項可以被刪除,並且約束通過不以'0'開始的註冊號進一步限制它。

DELETE 
    r1 
FROM 
    Registration r1 
JOIN 
    Registration r2 ON RIGHT(r1.RegistrationNumber, 8) = r2.RegistrationNumber 
WHERE 
    LEFT(r1.RegistrationNumber, 1) <> '0' 

運行上面的DELETE後,你的表看起來像這樣。我在一個SQL Server 2008實例上測試了它。

ID   RegistrationNumber 
----------- ------------------ 
2   483877668 
3   019000702 
4   837478848 
5   464657588 
7   042400065 
0

該解決方案將不依賴於登記號是一個特定的長度,它只是將查找是相同的整數,尚未相同的值(因爲前導零的)的那些和選擇用於具有'0'作爲第一個字符的條目。

DELETE r 
FROM Registration AS r 
JOIN Registration AS r1 ON r.RegistrationNo = CAST(r1.RegistrationNo AS INT) 
    AND r.RegistrationNo <> r1.RegistrationNo 
WHERE CHARINDEX('0',r.registrationno) = 1