2006/06/27

Querying a view takes ages - really weird SQL Server 2005 behaviour

There is a view called VIEW_TITLES. It is quite complicated. Executing a SELECT query against it returns 189 rows.

A query:
  SELECT TOP 200 *
  FROM dbo.VIEW_TITLES
takes 13 seconds to execute.

However, executing an identical, when it comes to the returned rows, query:
  SELECT *
  FROM dbo.VIEW_TITLES
takes an indefinite amount of time - I cancelled the execution after 5 minutes.

I have no idea how to explain this behaviour. It looks like a bug in the optimizer to me.

The only workaround I found looks like this:
  SELECT TOP (SELECT COUNT(*) FROM dbo.VIEW_TITLES) *
  FROM dbo.VIEW_TITLES

I know it's a pretty dirty hack, but it works. And it is still better than hard-coding some fixed number in the TOP expression.

No comments:

Post a Comment