tags:

views:

75

answers:

3

The following SQL run against a table with 1 million records is giving the same value for columns Date1 and Date2, and it took 38 seconds to execute. Is this an expected behavior and why?

CREATE FUNCTION Fn_Test(@a decimal)RETURNS TABLE
AS
RETURN
(
    SELECT @a Parameter, Getdate() Date1, PartitionTest.*
    FROM PartitionTest
);

SELECT *, GETDATE() Date2 FROM Fn_Test(RAND(DATEPART(s,GETDATE())))

Is this some kind of caching?

+5  A: 

Yes. SQL semantics do no require that a non-deterministic function that does not depend on the current row to be evaluated for each row. It is allowed to evaluate the function once and return the same value for all subsequent rows.

Remus Rusanu
In effect calling getdate in combination with a 'real' select simply bloats the resultset
Steve De Caux
Can you check this question too [http://stackoverflow.com/questions/1819513/big-performance-difference-1hr-to-1-minute-found-in-sql-can-you-explain-why]
Faiz
And what can be done if we need the time at which a particular row was fetched?
Faiz
You can't get the time a particular row was 'fetched' because that contradict the fundamental relational algebra that powers SQL as a language. You describe the desired result set, the engine returns the result set. Even if you could times from the underlying operations the 'fetch' time of a query is a pretty loose concept, given that a row can suffer several transofrmations during execution, can be spooled, read multiple times, etc etc.
Remus Rusanu
@Remus: Thanks for the comment. But can you explain why SQL prefers to evaluate parameters of a table valued function for each row processed inside the function (as given in the question in my comment above) ?
Faiz
'evaluate for each row processed inside a function' is a procedural statement in which you expect a certain execution path and order.
Remus Rusanu
A: 

GETDATE() (and CURRENT_TIMESTAMP) return the timestamp of the start of the transaction

just somebody
I tried this: BEGIN TRANSACTION; SELECT CURRENT_TIMESTAMP; EXECUTE LongRunningProc; SELECT CURRENT_TIMESTAMP; COMMIT TRANSACTION; -- and got different results for CURRENT_TIMESTAMP.
onedaywhen
A: 

SqlServer is performing a the GETDATE() at first and then replaces the value trough all the rows.

NeuroSys
Then can you answer why [http://stackoverflow.com/questions/1819513/big-performance-difference-1hr-to-1-minute-found-in-sql-can-you-explain-why] is happening?
Faiz