我正在寻找删除所有表内容的更好方法。当前,我们的过程如下图所示。不幸的是,它似乎有不同的问题,例如强制序列化,函数联接...。在每个测试在4个不同的数据库上并行执行测试之后,会花费很多时间。有没有更好的方法(更快,更好的性能)?即使对当前查询进行优化也没问题。
IF (OBJECT_ID('delete_tables') IS NOT NULL)
DROP PROCEDURE delete_tables
GO
CREATE PROCEDURE delete_tables AS
BEGIN
DECLARE @table_name VARCHAR(255);
DECLARE @tablenames TABLE (table_name VARCHAR(255));
DECLARE @tablenamestmp TABLE (table_name VARCHAR(255));
DECLARE @text NVARCHAR(MAX);
INSERT INTO @tablenames
SELECT st.name
FROM sys.tables st
INNER JOIN sys.schemas ss ON st.schema_id = ss.schema_id
INNER JOIN sys.partitions sp ON sp.object_id = st.object_id
WHERE st.is_ms_shipped = 0
AND ss.name = 'dbo'
AND sp.index_id IN (1,0)
AND st.name NOT LIKE 'comm_specialtable_%'
GROUP BY st.name
HAVING SUM(sp.rows) > 0
INSERT INTO @tablenamestmp
SELECT * FROM @tablenames;
WHILE EXISTS (SELECT 1 FROM @tablenamestmp)
BEGIN
SELECT TOP 1 @table_name = table_name
FROM @tablenamestmp;
IF @table_name IS NOT NULL
BEGIN
SET @text = 'ALTER TABLE '+ @table_name+ ' NOCHECK CONSTRAINT ALL'
EXEC sp_executesql @text;
END
DELETE FROM @tablenamestmp WHERE table_name = @table_name;
END
INSERT INTO @tablenamestmp SELECT * FROM @tablenames;
WHILE exists(SELECT 1 FROM @tablenamestmp)
BEGIN
SELECT TOP 1 @table_name = table_name FROM @tablenamestmp;
IF @table_name IS NOT NULL
BEGIN
SET @text = 'SET QUOTED_IDENTIFIER ON; DELETE FROM '+ @table_name
EXEC sp_executesql @text;
SET @text = 'ALTER TABLE '+ @table_name+ ' WITH CHECK CHECK CONSTRAINT all'
EXEC sp_executesql @text;
END
DELETE FROM @tablenamestmp WHERE table_name = @table_name;
END
end
答案 0 :(得分:1)
您可以使用TRUNCATE TABLE代替注释中提到的DELETE FROM来避免日志记录-但是,为什么要首先这样做呢?如果使用的是EF,则使用内存数据库;如果使用的是SQL的最新版本,则使用数据库快照;或者删除数据库并发布新的空白数据库;或者拥有初始状态的备份并将其恢复到顶部,则将使用可能都是更好的方法。