shahgols (5/1/2014)
Hi all,We have a very expensive query that I am tring to rewrite, but the rewritten query (even though is much faster) doesn't return the same number of records. I'm desperate for some help, thank you very much.
Before:
SELECT a.col1
,a.Id AS col2
,(
SELECT col3
FROM (
SELECT e.col3
,ROW_NUMBER() OVER (
PARTITION BY d.col2 ORDER BY d.[col4]
) AS ROWNUMBER
FROM db1.dbo.table1 d(NOLOCK)
INNER JOIN db1.dbo.[table2] e(NOLOCK) ON d.[col4] = e.col5
WHERE d.col2 = a.Id
AND e.col6 = 505
) x
WHERE ROWNUMBER = 1
) AS callcol41
FROM db1.dbo.table2 a(NOLOCK)
After:
SELECT a.col1
,a.Id AS col2
,col3 AS callcol41
FROM (
SELECT e.col3
,ROW_NUMBER() OVER (
PARTITION BY d.col2 ORDER BY d.[col4]
) AS ROWNUMBER
,a.col1
,a.Id
FROM db1.dbo.table1 d(NOLOCK)
INNER JOIN db1.dbo.[table2] e(NOLOCK) ON d.[col4] = e.col5
LEFT OUTER JOIN db1.dbo.table2 a ON d.col2 = a.Id
AND e.col6 = 505
) x
WHERE ROWNUMBER = 1
Try getting rid of that NOLOCK hint first. Are you ok with randomly returning extra and/or missing rows?
http://sqlblogcasts.com/blogs/tonyrogerson/archive/2006/11/10/1280.aspx
http://blogs.msdn.com/b/davidlean/archive/2009/04/06/sql-server-nolock-hint-other-poor-ideas.aspx
http://www.jasonstrate.com/2012/06/the-side-effect-of-nolock/[/url]
_______________________________________________________________
Need help? Help us help you.
Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.
Need to split a string? Try Jeff Modens splitter http://www.sqlservercentral.com/articles/Tally+Table/72993/.
Cross Tabs and Pivots, Part 1 – Converting Rows to Columns - http://www.sqlservercentral.com/articles/T-SQL/63681/
Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs - http://www.sqlservercentral.com/articles/Crosstab/65048/
Understanding and Using APPLY (Part 1) - http://www.sqlservercentral.com/articles/APPLY/69953/
Understanding and Using APPLY (Part 2) - http://www.sqlservercentral.com/articles/APPLY/69954/