简体   繁体   中英

SQL query to run 3 step (Select-Insert-delete) on linked server

I have a linked server to mysql in SQL Server 2008.

I'm looking for a stored procedure to do these 3 steps:

  1. select from mysql
  2. insert selected value into SQL Server
  3. delete the selected value from mysql

Before doing with linked server there was a witness machine and that machine this these steps programmatically like this :

Pseudo code :

SELECT values from source
if($row>0)
    {
    foreach ($row as $rows)
    {
        INSERT INTO dest (selected value from source)
        Delete from  source
        }
    }

in programmatically way I do a loop and I know exactly when insert happen then I remove the source value, but how can I implement this fail-safe in a stored procedure and a daily job ?

This is my insert code method without delete :

declare @count bigint
select @count = max(id) from dest.table

INSERT INTO dest.table(ID)
    SELECT TOP 50000 ID
    FROM [sourceLinkedServer].[db].[table] 
    WHERE ID > @count

Perhaps something like this will do the job:

create table #temp (ID int, value varchar(20))

insert into #temp(ID,value)
select top 50000 value from [sourceLinkedServer].[db].[table]
where ID > (select max(ID) from destTable)
order by ID   

insert into destTable (value)
select value from #temp

delete ls 
from [sourceLinkedServer].[db].[table] as ls
where exists (select 1 from #temp as t where t.id = ls.ID)

drop table #temp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM