Hi all,
I'm attempting to get some numbers from an XAL database (MS SQL Server 2005). My query is below.
There are some conditions commented out. If I add either one of the lower ones the query executes in a matter of seconds but if I replace them with the top one it takes forever (7 minutes and counting).
Can anyone give me some pointers for how to get both conditions in my query without it taking forever?
SELECT DISTINCT
SALESTRANS.MONTSLUT AS INVOICEDATE,
SALESTABLE.DATASET,
DEBTABLE.[NAME] AS DEBITORNAME,
DEBTABLE.ACCOUNTNUMBER AS ACCOUNTNUMBER,
SALESTABLE.SALESREP,
SALESTABLE.SALESNUMBER,
SALESTRANS.DEPARTMENT,
SALESTRANS.CENTRE,
SALESTRANS.PURPOSE,
SALESTRANS.QTYORDERED AS ANTAL_BESTILT,
STOCKTABLE.ITEMNUMBER AS VARENUMMER,
STOCKTABLE.ITEMNAME AS VARENAVN,
(SALESTRANS.LINEAMOUNT * (CASE WHEN SALESTABLE.EXCHANGECODE <> '' THEN ex.EXCHRATE ELSE 1 END))
AS SALESPRICEDKK,
SALESTRANS.LINEAMOUNT,
SALESTRANS.QTYORDERED AS ANTAL,
ex.EXCHRATE AS EXCHRATE,
ex.EXCHANGECODE,
ex.ROWNUMBER
FROM SALESTRANS
INNER JOIN SALESTABLE ON SALESTRANS.SALESNUMBER = SALESTABLE.SALESNUMBER
INNER JOIN STOCKTRANS ON SALESTRANS.TRANSID = STOCKTRANS.TRANSID
INNER JOIN DEBTABLE ON SALESTABLE.DEBTORACCOUNT = DEBTABLE.ACCOUNTNUMBER
INNER JOIN STOCKTABLE ON SALESTRANS.ITEMNUMBER = STOCKTABLE.ITEMNUMBER
LEFT JOIN EXCHANGECODERATE ex ON SALESTRANS.EXCHANGECODE = ex.EXCHANGECODE
WHERE (SALESTABLE.DATASET='DAT')
AND (STOCKTABLE.DATASET='DAT')
AND (STOCKTRANS.SALESPROJ = (' ' + SALESTABLE.SALESNUMBER))
AND (SALESTABLE.SALESNUMBER = SALESTRANS.SALESNUMBER)
AND SALESTRANS.MONTSLUT > '01-01-2008'
AND SALESTABLE.SALESPHASE <> 0
--AND (SALESTABLE.EXCHANGECODE = ''
--OR ex.ROWNUMBER = (SELECT MAX(ROWNUMBER) FROM EXCHANGECODERATE WHERE EXCHANGECODE = ex.EXCHANGECODE))
--AND SALESTABLE.EXCHANGECODE = ''
--AND ex.ROWNUMBER = (SELECT MAX(ROWNUMBER) FROM EXCHANGECODERATE WHERE EXCHANGECODE = ex.EXCHANGECODE
ORDER BY SALESTABLE.SALESNUMBER