Hey guys, I have a script to add/update members in...
# sql
g
Hey guys, I have a script to add/update members in our members table. I ran it on an import table with 6K records and it finished in just a few seconds. But an import table with 96K rows it has been running over 90 minutes! Thoughts? https://pastebin.com/GL6FRTsC
a
Any reason for using a cursor instead of JOINs? Since a cursor processes row by row, a single INNER JOIN for updates (member id exists) and LEFT JOIN for inserts (member id is null) should be way faster.
3
g
Hmm, I don't follow.
I thought I have to loop over the import table records and if they exist do an update, otherwise do an insert.
I feel like I wrote something wrong and maybe it's running out of memory or something. There's no logical reason it can't do this in under 2 minutes based on the smaller imports I've done with it.
a
From what I see, there is no reason you can't achieve the same result with 2 JOIN statements, instead of a cursor
s
a single left join might even suffice or maybe i'm missing something
👍 2
look up upsert/merge into for a lead, may need a window function to get the top memberid, i'd probably use a cte there
a
@s1deburn - Yes, technically it could be a single statement. Personally I prefer old style (2 statements) for clarity, but either works
@gus_dancy - I have to jump on a call, but here's an example of what I mean.  https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=438e7a6bc4e831f7bbe33ec5ce772a15
g
Oh, that is interesting.
a
Look into what @s1deburn suggested too. It's the same concept, but using 1 statement versus 2
g
I think you need to have two sqls, one for insert and one for update. Then you should get consistent performance. With cursor or similar (which process record by record), it would take long time.
The current solution, might caused locking issue since it need long time to run. It might be slow, but should not that slow.
a
What indexes exist on the tables?