Running MS SQL Server 2008, if I execute the following query, it runs quite fast (2 seconds or less) and returns 906 rows:
DECLARE @ValueTime datetime2
DECLARE @PriceUpdTime datetime2
SELECT @ValueTime = '2014-11-28 23:00:00.000000'
SELECT @PriceUpdTime = CURRENT_TIMESTAMP
SELECT *
FROM dbo.fMyTableFunction(@PriceUpdTime, @ValueTime) AS prices
However, when I move this code into a stored procedure:
CREATE PROCEDURE dbo.MDMTmp
(
@ValueTime datetime2 = NULL,
@PriceUpdTime datetime2 = NULL
)
AS
BEGIN
SET NOCOUNT ON;
IF @PriceUpdTime IS NULL
SELECT @PriceUpdTime = CURRENT_TIMESTAMP
SELECT *
FROM dbo.fMyTableFunction(@PriceUpdTime, @ValueTime) AS prices
END
the call
EXEC dbo.MDMTmp '2014-11-28 23:00:00.000000', NULL
runs much slower (takes forever - I stopped waiting after 30 minutes).
While experimenting, I just placed the code without parameters into a stored procedure like this
CREATE PROCEDURE dbo.MDMTmpVars AS
BEGIN
DECLARE @ValueTime datetime2
DECLARE @PriceUpdTime datetime2
SELECT @ValueTime = '2014-11-28 23:00:00.000000'
SELECT @PriceUpdTime = CURRENT_TIMESTAMP
SELECT *
FROM dbo.fMyTableFunction(@PriceUpdTime, @ValueTime) AS prices
END
and then executed
EXEC dbo.MDMTmpVars
which worked like a charm – same 906 rows in 1 second. Any idea what could be wrong and how to make the original stored procedure work?
UPDATE If I only pass one of the 2 parameters like this
ALTER PROCEDURE dbo.MDMTmp
(
@ValueTime datetime2 = NULL
)
AS
BEGIN
SET NOCOUNT ON;
DECLARE @PriceUpdTime datetime2
SELECT @PriceUpdTime = CURRENT_TIMESTAMP
IF @PriceUpdTime IS NULL
SELECT @PriceUpdTime = CURRENT_TIMESTAMP
SELECT *
FROM dbo.fBondTickerValueAtRunValueDTs(@PriceUpdTime, @ValueTime) AS prices
END
and then execute
EXEC dbo.MDMTmp '2014-11-28 23:00:00.000000'
it works ok, but if I make PriceUpdTime
a parameter instead, it does not work, either if I pass NULL
or today's date as a string.
UPDATE 2 Here is what worked also:
ALTER PROCEDURE dbo.MDMTmp
(
@ValueTimeIn datetime2 = NULL,
@PriceUpdTimeIn datetime2 = NULL
)
AS
BEGIN
SET NOCOUNT ON;
IF @PriceUpdTimeIn IS NULL
SELECT @PriceUpdTimeIn = CURRENT_TIMESTAMP
DECLARE @ValueTime datetime2
DECLARE @PriceUpdTime datetime2
SELECT @ValueTime = @ValueTimeIn
SELECT @PriceUpdTime = @PriceUpdTimeIn
SELECT *
FROM dbo.fBondTickerValueAtRunValueDTs(@PriceUpdTime, @ValueTime) AS prices
END
and then executing either of
EXEC dbo.MDMTmp '2014-11-28 23:00:00.000000', NULL
EXEC dbo.MDMTmp '2014-11-28 23:00:00.000000', '2015-02-10'
So perhaps is parameter sniffing, how do i fix it?