Here’s what I’d like to do.
For each table in linkedserver.database whose tablename is like ‘text%’
(inside loop)
A. If current_table exists locally, drop it
B. select * into table.name (local) from linkedserver.tablename (copy
schema + data)C. Possibly check for errors and Print some text about it?
Next
Any idea if this script is possible? I’m very clueless about working with table names if it would be possible to
select * into @Variable_Storing_Table_Name
from LinkedServer.DB.@Variable_Storing_Table_Name
Well, here’s how to do this using a
cursor:While cursors should generally be avoided, here you’re looking to do a lot of logic behind each and every row. So, here it is. What it does is grab all of the linked tables and match any of the local tables to those, or
nullif the local table doesn’t exist. This places it in acursor, which we can use to iterate through the rowset.The
fetch nextcommand grabs the next row from ourcursorand then applies your logic to it (dropit if the local table exists, then do aselect * into...).You can catch errors one of two ways. I used the
try...catchblock, but you can also check@@ERRORand see if it’s not equal to zero. Really, whatever you feel most comfortable with.As a disclaimer for the anti-cursor crowd: Cursors aren’t evil, they’re just often used improperly.