SQL Server Same Query, Same Server, different database query runs super slow

e5nqia27  于 2023-04-28  发布在  其他
关注(0)|答案(1)|浏览(180)

Wrote a view in a database. The view takes 0 seconds to run when called from 1 database and 2.5 minutes when called from another.

I have created a video that best describes this problem. Watch it here: https://youtu.be/jEqI2bUyelQ

I tired to re create the view by dropping it. I tried to compare the query execution plans, they are different when run with 1 database vs the other. I looked into the query it self and noticed that if you remove the where clause the performance is regained and it takes the same amount of time for both.

Expected results are that it should take 0 seconds to run from no matter what database the view is being called from.

Here is the SQL script:

SELECT 
    cus.MacolaCustNo,
    dsp.cmp_code ,
    count(distinct dsp.item_no) AS InventoryOnDisplay,
    (SELECT max(dsp.LastSynchronizationDate)
    FROM Hinkley.dbo.vw_HH_next_Capture_date ) AS UpdatedDate,
    case
        WHEN DATEADD(DAY, 90, isnull(max(dsp.LastSynchronizationDate),'1/1/1900')) >= 
            (SELECT max(dsp.LastSynchronizationDate)
                FROM Hinkley.dbo.vw_HH_next_Capture_date ) 
            THEN 'Compliant'
        WHEN DATEADD(DAY, 90, isnull(max(dsp.LastSynchronizationDate),'1/1/1900')) <= 
            (SELECT max(dsp.LastSynchronizationDate)
            FROM Hinkley.dbo.vw_HH_next_Capture_date )
            AND DATEADD(DAY, 90, isnull(max(dsp.LastSynchronizationDate),'1/1/1900')) >= getdate() 
            THEN 'Warning'
        ELSE 'Non-Compliant'
    END AS Inventory_Status
FROM 
    Hinkley.dbo.HLIINVDSP_SQL dsp (nolock)
INNER JOIN 
    [DATA].dbo.vw_HLI_Customer (nolock) cus
        ON cus.CusNo = dsp.cmp_code
WHERE 
    cus.cust_showroom = 1
    AND 
    cus.active_y = 1
GROUP BY cus.MacolaCustNo,dsp.cmp_code
n8ghc7c1

n8ghc7c11#

Check the compatibility level between yours databases. https://learn.microsoft.com/en-us/sql/relational-databases/databases/view-or-change-the-compatibility-level-of-a-database?view=sql-server-ver16

If it is different, leave both databases at the same compatibility level and try again.

相关问题