我已经编写了此存储过程,用于从我的一张表中清除数据。我已将其配置为可存档数据或进行硬删除。由于数据量很小,因此我使用循环来执行相同的操作。它的删除部分工作正常,但是其中的存档部分使我很难受,并且我多次尝试都卡在了那里。这是我的SP。
ALTER PROCEDURE [dbo].[spPurgeRecords_new] (
@Age AS INT,
@NumberOfLoops AS BIGINT,
@DeleteSize BIGINT,
@IsArchive BIT
)
AS
SET NOCOUNT ON
SET XACT_ABORT ON
BEGIN
DECLARE @CurrentLoop AS BIGINT;
SET @CurrentLoop = 0
declare @cutoffDate datetime;
declare @maxXDate datetime;
declare @loop varchar(50);
select @cutoffDate = dateadd(year,-@Age,getdate())
select @maxXDate = max(dateCreated) from cbr_audit where dateCreated < @cutoffDate
declare @date varchar(100), @cmd varchar(1000),@archivedate varchar(100)
set @date = (select FORMAT(getdate(), 'yyyyMMdd'));
set @archivedate = (select FORMAT(@maxXDate, 'yyyyMMdd'));
declare @backupTable varchar(100)
set @backupTable = 'cbr_audit_Backup_' + @date;
BEGIN TRY
BEGIN TRANSACTION
WHILE @CurrentLoop < @NumberOfLoops
BEGIN
IF @IsArchive = 1
BEGIN
--Archive the records into a backup table
IF OBJECT_ID (@backupTable, N'U') IS NULL
begin
set @cmd = 'SELECT * INTO [cbr_audit_Backup_'+ @date +'] FROM [cbr_audit] WITH (NOLOCK) where convert(datetime,dateCreated,101) <= CONVERT(DATETIME, ''' + @archivedate + ''', 101)'
exec(@cmd)
end
--Delete the rows from cbr_audit table
DELETE
FROM dbo.cbr_audit
WHERE id IN
(SELECT TOP(@DeleteSize) id
FROM dbo.cbr_audit WITH (NOLOCK)
WHERE dateCreated <= @maxXDate);
END
ELSE
BEGIN
-- Delete the records
DELETE
FROM dbo.cbr_audit
WHERE id IN
(SELECT TOP(@DeleteSize) id
FROM dbo.cbr_audit WITH (NOLOCK)
WHERE dateCreated <= @maxXDate);
END
-- WAITFOR DELAY '00:00:00:500';
SET @CurrentLoop = @CurrentLoop + 1;
set @loop = cast(@currentloop as varchar(50))
RAISERROR (@loop, 0, 1) WITH NOWAIT
END
COMMIT TRANSACTION
END TRY
BEGIN CATCH
--Rollback
RETURN
END CATCH
END
在此SP中,在代码的存档部分中,动态sql没有给出任何结果。 DateCreated是Datetime类型。有人可以帮我吗在此先感谢。
似乎您正在使用SQL 2016或更高版本,请尝试使用CONCAT,类似:
set @cmd = concat('SELECT * INTO [cbr_audit_Backup_'+ @date +'] FROM [cbr_audit] WITH (NOLOCK) where convert(datetime,dateCreated,121) <= ', CONVERT(varchar(30), @archivedate , 121))
更多的东西:我强烈建议您始终使用样式121(规范)