views:

17

answers:

3

I apologize in advance for my newbness! Using SQL Server 2005 (9.00.4053.00).

It takes 2:22 to run this query:

DECLARE @Start_date CHAR(10);
SET @Start_date = '2010-07-01';

SELECT 
    DATEPART(wk, rp.dtScanDate) AS 'Week Number',
    COUNT(rp.qwImageID) AS 'Documents',
    SUM(CAST(rp.iCompressedSize AS BIGINT))/1024/1024 AS 'Compressed',
    SUM(CAST(rp.iUncompressedSize AS BIGINT))/1024/1024 AS 'Uncompressed'
INTO [#TempRVOSPolicy]
FROM
    Policy rp
WHERE
    dtScanDate >= @Start_date
GROUP BY 
    DATEPART(wk, rp.dtScanDate)
ORDER BY
    DATEPART(wk, rp.dtScanDate);

But it takes 0:00 to run this one:

DECLARE @Start_date CHAR(10);
SELECT 
    DATEPART(wk, rp.dtScanDate) AS 'Week Number',
    COUNT(rp.qwImageID) AS 'Documents',
    SUM(CAST(rp.iCompressedSize AS BIGINT))/1024/1024 AS 'Compressed',
    SUM(CAST(rp.iUncompressedSize AS BIGINT))/1024/1024 AS 'Uncompressed'
INTO [#TempRVOSPolicy]
FROM
    Policy rp
WHERE
    dtScanDate >= '2010-07-01'
GROUP BY 
    DATEPART(wk, rp.dtScanDate)
ORDER BY
    DATEPART(wk, rp.dtScanDate);

Why is this?

A: 

Take a look at the Query Plan that SQL Server generates.

My guess is that the query optimizer optimizes away the cast from char(10) to datetime (does it a single time) in the second query whereas it needs to cast the value once for each row in the first.

Justin Niessner
+1  A: 

what happens when you do this?

DECLARE @Start_date datetime;
SET @Start_date = '20100701';
SQLMenace
It took roughly the same time to complete. A little under 3 minutes.
nvahalik
What dataype is dtScanDate and what does the execution plan show?
SQLMenace
dtScanDate is a datetime value. The execution plan shows a clustered index scan as the most expensive operation (99%).[Policy].[dbo].[{44469590-70B7-48BC-A262-8D131EC8E396}].[dtScanDate]>=[@Start_date]
nvahalik
It also appears that the latter query uses a key lookup and an index seek. The second one does not.
nvahalik
A: 

If you always run one query after another, it may return you cashed result (for second query)...

a1ex07