How to Move Rows from Table A to B and Select Only the Moved Rows from A?
-
14-06-2021 - |
سؤال
I need to move all existing rows in table A over to table B. I also need to select ONLY the moved rows from table A. (Not from Table B since Table B is an archive and contains a lot of rows which will result in the select taking a lot of time)
I'm using Microsoft SQL Server 2008 and .Net (System.Data.SqlClient)
Please note that records are inserted continuously to Table A. I need to ensure only the moved records are selected and that they are selected from Table A before they are deleted.
What is the most efficient way to do this?
المحلول 3
I was finally able to solve this issue by using the SQL Server's OUTPUT clause. Have a look below. IMO I see no reason why this method would hold any unnecessary locks either.
declare @TempTable TABLE(Col1 bigint, Col2 varchar(50))
delete from TableA
output Deleted.Col1, Deleted.Col2 INTO @TempTable
insert into TableB (Col1, Col2)
select Col1, Col2 from @TempTable
select Col1, Col2 from @TempTable
Thanks you all for your help.
نصائح أخرى
Can't you do something like this:
BEGIN TRANSACTION;
SELECT * FROM source WITH (HOLDLOCK)
WHERE ...
DELETE source
OUTPUT deleted.* INTO destination
WHERE ...;
COMMIT TRANSACTION;
Of course you wouldn't use SELECT * but I don't know your tables so...
To what I understand you would like to do something like this:
SELECT []
INTO archivetable
FROM activetable
SELECT []
FROM activetable
WHERE id in (SELECT id from archivetable)
DELETE
FROM activetable
WHERE id in (SELECT id from archivetable)
this will copy, select and delete in a somewhat safe way.