ffarouqi - Wednesday, February 14, 2018 12:29 AM
Table variables are slow (and you can probably manage with only one or even none).
Cursors are slow
Your string split is probably slow (can't tell, it wasn't included)
The variable assignments can be done in a single statement.
Can't tell how the final insert can be optimised. The multiple DISTINCTS are probably unnecessary though.
ffarouqi - Tuesday, February 13, 2018 3:37 PM
So give it a shot. You'll learn a lot more by trying and getting suggestions than by someone doing it for you.
If you want your code (not just this) optimising by someone else, suggest to your boss that you get a consultant in to look at it.
Gail Shaw
Microsoft Certified Master: SQL Server, MVP, M.Sc (Comp Sci)
SQL In The Wild: Discussions on DB performance with occasional diversions into recoverability