我想在SQL Server数据库中获取一部分数据,因此我可以为应用程序运行一些冒烟测试。我的典型工作流程如下,但删除查询需要一个多小时,因为X,Y和Z中有数亿行。如何才能更快地完成此操作?为清楚起见,请在答案中使用T-SQL代码。
通过为每个表运行此命令来备份每个表:
SELECT * INTO BACKUP_SRC_PATIENT FROM [SRC_PATIENT] -- has PK patient_id
SELECT * INTO BACKUP_SRC_X FROM [SRC_X] -- has FK patient_id
SELECT * INTO BACKUP_SRC_Y FROM [SRC_Y] -- has FK patient_id
SELECT * INTO BACKUP_SRC_Z FROM [SRC_Z] -- has FK patient_id
删除所有100名患者
DELETE FROM [SRC_PATIENT]
WHERE [PATIENT_ID_NONNUM] NOT IN
(SELECT top 100 [PATIENT_ID] FROM [SRC_PATIENT]
WHERE BLA = 'BLA')
从SRC_X,SRC_Y和SRC_Z删除数据,其中patient_id不在SRC_PATIENT中
DELETE FROM [SRC_X]
WHERE [PATIENT_ID] NOT IN
(SELECT [PATIENT_ID] FROM [SRC_PATIENT])
DELETE FROM [SRC_Y]
WHERE [PATIENT_ID] NOT IN
(SELECT [PATIENT_ID] FROM [SRC_PATIENT])
DELETE FROM [SRC_Z]
WHERE [PATIENT_ID] NOT IN
(SELECT [PATIENT_ID] FROM [SRC_PATIENT])
答案 0 :(得分:0)
而不是删除除100之外的所有行 - 截断表并从备份中复制超过100行。
TRUNCATE剪辑表格中的所有数据,而不必逐行删除(或逐页逐页删除):
TRUNCATE TABLE [SRC_PATIENT]
TRUNCATE TABLE [SRC_X]
TRUNCATE TABLE [SRC_Y]
TRUNCATE TABLE [SRC_Z]
INSERT INTO [SRC_PATIENT]
SELECT TOP 100 * FROM [BACKUP_SRC_PATIENT]
WHERE BLA = 'BLA'
INSERT INTO [SRC_X]
SELECT * FROM [BACKUP_SRC_X]
WHERE [PATIENT_ID] IN (SELECT [PATIENT_ID] FROM [SRC_PATIENT])
INSERT INTO [SRC_Y]
SELECT * FROM [BACKUP_SRC_Y]
WHERE [PATIENT_ID] IN (SELECT [PATIENT_ID] FROM [SRC_PATIENT])
INSERT INTO [SRC_Z]
SELECT * FROM [BACKUP_SRC_Z]
WHERE [PATIENT_ID] IN (SELECT [PATIENT_ID] FROM [SRC_PATIENT])
答案 1 :(得分:0)
使用架构开关,然后将所需的行拉入非备份表
您需要创建一个具有相同元数据的表,但切换几乎立即发生。
CREATE TABLE dbo.Backup-Table1
(Col1 int
Col2 int)
ALTER TABLE dbo.Table1
SWITCH TO dbo.Backup-Table1
INSERT INTO dbo.Table1
SELECT TOP 100 *
FROM dbo.Backup-Table1
WHERE Condition = Met