James Parish
James Parish

Reputation: 337

optimising/simplifying cursor sql

i've got the below code, and it operates just fine, only it takes a couple of seconds to calculate the answer - i was wondering whether there is a quicker/neater way of writing this code - and if so, what am i doing wrong?

thanks

select case when
    (select LSCCert from matterdatadef where ptmatter=$Matter$) is not null then
    (
        (select case when
            (SELECT top 1 dbo.matterdatadef.ptmatter 
             From dbo.workinprogress, dbo.MatterDataDef 
             where  ptclient=(
                 select top 1 dbo.workinprogress.ptclient 
                 from dbo.workinprogress 
                 where dbo.workinprogress.ptmatter = $matter$)
               and dbo.matterdatadef.LSCCert=(
                 select top 1 dbo.matterdatadef.LSCCert 
                 from dbo.matterdatadef 
                 where dbo.matterdatadef.ptmatter = $matter$)
             )=ptMatter then (
                 SELECT isnull((DateAdd(mm, 6, (
                         select top 1 Date 
                         from OfficeClientLedger 
                         where (pttrans=3) 
                             and ptmatter=$matter$ 
                         order by date desc))), 
                     (DateAdd(mm, 3, (
                         SELECT DateAdd 
                         FROM LAMatter 
                         WHERE  ptMatter = $Matter$)))
             )
        )
        end 
        from lamatter 
        where ptmatter=$matter$)
    )
    end

Upvotes: 1

Views: 155

Answers (1)

Bohemian
Bohemian

Reputation: 425013

It looks like this your sql was generated from a reporting tool. The problem is you are executing the SELECT top 1 dbo.matterdatadef.ptmatter... query for every row of table lamatter. Further slowing execution, within that query you are recalculating comparison values for both ptclient and LSCCert - values that aren't going to change during execution.

Better to use proper joins and craft the query to execute each part only once by avoiding correlated subqueries (queries that reference values in joined tables and must be executed for every row of that table). Calculated values are OK, as long as they are calculated only once - ie from within the final where clause.

Here is a trivial example to demonstrate a correlated subquery:

Bad sql:

select a, b from table1 
where a = (select c from table2 where d = b)

Here the sub-select is run for every row, which will be slow, especially without an index on table2(d)

Better sql:

select a, b from table1, table2
where a = c and d = a

Here the database will scan each table at most once, which will be fast

Upvotes: 1

Related Questions