SQL 服务器中的安全 move/archive 行
Safely move/archive Rows in SQL Server
我有这个SQL-script/sp
BEGIN TRAN
BEGIN TRY
INSERT INTO TblDest
SELECT * FROM TblSource
DELETE FROM TblSource
COMMIT TRAN
END TRY
BEGIN CATCH
ROLLBACK TRAN
END CATCH
它将 TblSource 中的所有行移动到 TblDest。我想确保在完成此备份时插入的任何行都保留在 TblSource 中。
如果我在 DELETE 行之前设置一个断点并打开另一个 window 并在 TestSource 中插入一个新行,然后完成脚本,新行将被删除。
我需要一个 Temp-table 还是我可以锁定整个 table?
您可以尝试如下查询。
BEGIN TRAN
BEGIN TRY
INSERT INTO TblDest SELECT * FROM TblSource
DELETE FROM TblSource where [SomeId] in (select id from TblDest)
COMMIT TRAN
END TRY
BEGIN CATCH
ROLLBACK TRAN
END CATCH
您可以使用 HOLDLOCK
提示:
INSERT INTO TblDest
SELECT * FROM TblSource WITH (HOLDLOCK)
DELETE FROM TblSource
HOLDLOCK Is equivalent to SERIALIZABLE. HOLDLOCK applies only to the table
or view for which it is specified and only for the duration of the
transaction defined by the statement that it is used in. HOLDLOCK
cannot be used in a SELECT statement that includes the FOR BROWSE
option.
来自 MSDN:Table hints
我有这个SQL-script/sp
BEGIN TRAN
BEGIN TRY
INSERT INTO TblDest
SELECT * FROM TblSource
DELETE FROM TblSource
COMMIT TRAN
END TRY
BEGIN CATCH
ROLLBACK TRAN
END CATCH
它将 TblSource 中的所有行移动到 TblDest。我想确保在完成此备份时插入的任何行都保留在 TblSource 中。
如果我在 DELETE 行之前设置一个断点并打开另一个 window 并在 TestSource 中插入一个新行,然后完成脚本,新行将被删除。
我需要一个 Temp-table 还是我可以锁定整个 table?
您可以尝试如下查询。
BEGIN TRAN
BEGIN TRY
INSERT INTO TblDest SELECT * FROM TblSource
DELETE FROM TblSource where [SomeId] in (select id from TblDest)
COMMIT TRAN
END TRY
BEGIN CATCH
ROLLBACK TRAN
END CATCH
您可以使用 HOLDLOCK
提示:
INSERT INTO TblDest
SELECT * FROM TblSource WITH (HOLDLOCK)
DELETE FROM TblSource
HOLDLOCK Is equivalent to SERIALIZABLE. HOLDLOCK applies only to the table or view for which it is specified and only for the duration of the transaction defined by the statement that it is used in. HOLDLOCK cannot be used in a SELECT statement that includes the FOR BROWSE option.
来自 MSDN:Table hints