从MSSQL中的表中删除旧条目

问题描述 投票:-1回答:3

我的MSSQL数据库中的表超过500MB。我想删除x最后的条目,所以表大小只有100MB。这应该是每周运行一次的任务。我怎么能这样做?

例:

删除旧条目前的表:

删除旧条目后的表格:

sql sql-server sql-server-ce
3个回答
0
投票

您可以使用DATALENGTH来获取特定列中的数据大小。使用窗口函数,您可以总计DATALENGTH值的运行总计。然后,您可以删除表中的所有记录,这些记录将超过所需的最大表大小。这是一个例子:

-- Sample table with a VARBINARY(MAX) column
CREATE TABLE tmp (id INT IDENTITY(1,1) PRIMARY KEY, col VARBINARY(MAX))

-- Insert sample data - 20 bytes per row.
;WITH cte AS 
(
    SELECT 1 AS rn, HASHBYTES('sha1', 'somerandomtext') t
    UNION all 
    SELECT rn + 1, HASHBYTES('sha1', 'somerandomtext')
    FROM cte
    WHERE rn< 5000  
)
INSERT INTO tmp (col)
SELECT t FROM cte
OPTION (maxrecursion 0)

-- @total_bytes is the desired size of the table after the delete statement
DECLARE @total_bytes int = 200

-- Use the SUM window function to get a running total of the DATALENGTH
-- of the VARBINARY field, and delete when the running total exceeds
-- the desired table size.
-- You can order the window function however you want to delete rows
-- in the correct sequence.
DELETE t
FROM tmp t
INNER JOIN
(
    SELECT id, SUM(DATALENGTH(col)) OVER (ORDER BY id) total_size
    FROM tmp
)sq ON t.id = sq.id AND sq.total_size > @total_bytes

现在检查tmp:10行中剩下的内容,“col”列的总大小与@total_bytes变量中指定的200字节大小相匹配。

更新:这是使用您的示例数据的示例:

CREATE TABLE tmp (id INT PRIMARY KEY, contact VARCHAR(100), country VARCHAR(25))
GO

INSERT INTO tmp VALUES 
(1, 'Maria Anders', 'Germany'),
(2, 'Francisco Chang', 'Mexico'),
(3, 'Roland Mendel', 'Austria'),
(4, 'Helen Bennett', 'UK'),
(5, 'Yoshi Tannamuri', 'Canada'),
(6, 'Giovanni Rovelli', 'Italy')
GO

-- @total_bytes is the desired size of the table after the delete statement
DECLARE @total_bytes INT = 40

-- Use the SUM window function to get a running total of the DATALENGTH
-- of the VARBINARY field, and delete when the running total exceeds
-- the desired table size.
-- You can order the window function however you want to delete rows
-- in the correct sequence.
DELETE t
FROM tmp t
INNER JOIN
(
    SELECT id, SUM(DATALENGTH(contact)) OVER (ORDER BY id)
        + SUM(DATALENGTH(country)) OVER (ORDER BY id) total_size
    FROM tmp
)sq ON t.id = sq.id AND sq.total_size > @total_bytes

SELECT * FROM tmp -- 2 rows left!

0
投票
DELETE FROM TABLE_NAME WHERE date_column < '2018-01-01';

这将删除2018年1月之前输入的所有数据


0
投票

如果你想删除最近7天的数据

delete from table_name WHERE date_column >= DATEADD(day,-7, GETDATE())
© www.soinside.com 2019 - 2024. All rights reserved.