我想从我的表中删除4个有多个记录的4个。我该怎么办?
Ex:-
Table1
1 a
2 b
3 c
4 d
5 e
6 f
7 g
8 h
9 i
我想删除每第4行。
我不想使用循环或光标。
答案 0 :(得分:3)
Delete A from
(
Select *,Row_Number() Over(Order By Id) as RN from TableA
) A
where RN%4=0
答案 1 :(得分:0)
试试这个......
delete from table_name where (col1 % 4) = 0
答案 2 :(得分:0)
使用WITH cte AS (
SELECT t.*, ROW_NUMBER() OVER (ORDER BY t.rowfield) AS rank
FROM Table1 t)
SELECT rowfield, fielda
FROM cte
WHERE rank%4 != 0
。
rowfield fielda
1 a
2 b
3 c
5 e
6 f
7 g
9 i
输出
DELETE FROM
SQL小提琴:https://github.com/mperham/sidekiq/blob/master/lib/sidekiq/extensions/action_mailer.rb
如果您对输出感到满意,请使用{{1}}。
答案 3 :(得分:0)
试试这个
DECLARE @nvalToDelete varchar(100)='4,7,3,8,9'-- just give values to delete from table
DECLARE @temp TABLE
(
valtodelete VARCHAR(100)
)
DECLARE @Deletetemp TABLE
(
valtodelete INT
)
INSERT INTO @temp
SELECT @nvalToDelete
INSERT INTO @Deletetemp
SELECT split.a.value('.', 'VARCHAR(1000)') AS valToDelete
FROM (SELECT Cast('<S>' + Replace(valtodelete, ',', '</S><S>')
+ '</S>' AS XML) AS valToDelete
FROM @temp) AS A
CROSS apply valtodelete.nodes('/S') AS Split(a)
DECLARE @Table1 TABLE
(
ID INT,
val varchar(10)
)
INSERT INTO @Table1
SELECT 1,'a' UNION ALL
SELECT 2,'b' UNION ALL
SELECT 3,'c' UNION ALL
SELECT 4,'d' UNION ALL
SELECT 5,'e' UNION ALL
SELECT 6,'f' UNION ALL
SELECT 7,'g' UNION ALL
SELECT 8,'h' UNION ALL
SELECT 9,'i'
SELECT *
FROM @Table1;
WITH cte
AS (SELECT *,
RN = Row_number()
OVER (
ORDER BY id )
FROM @Table1)
DELETE FROM @Table1
WHERE id IN(SELECT id FROM cte
WHERE rn IN (SELECT CASt(valToDelete AS INT) FROM @Deletetemp)
)
SELECT *
FROM @Table1
答案 4 :(得分:0)
这可以使用索引(如果存在)并使用numbers table
;with cte
as
(select n from numbers
where n%4=0
)
delete t
from table1 t
join
cte c
on c.n=t.id