I’m stuck on a sql server function, pasted below.. I’m trying to return a boolean (bit). I won’t bore you with the table schema description and nested udf functionality unless someone would like to see it, since when I test the two values I’m calculating individually, this works fine. I’m getting a value into two local variables, and comparing them. Again individually they work, yet when I run the function, I always get false (I got true in one instance with test data some time back but haven’t been able to recreate it for a while). So I wonder if my error is in my assignment statements near the end?
ALTER FUNCTION dbo.PricingVolDataAvailableToDateProvided
(@Ticker char,
@StartDate DATETIME2,
@NumberOfDaysBack int)
RETURNS bit
AS
BEGIN
DECLARE @Result bit
DECLARE @TargetDate DATETIME2
SET @TargetDate=dbo.TradingDateByStartDate(@NumberOfDaysBack, @StartDate)
DECLARE @DataPointDateFromTable DATETIME2
SET @DataPointDateFromTable= (SELECT TOP (1) TradeDate
FROM (SELECT TOP (@NumberOfDaysBack) TradeDate, Symbol
FROM tblDailyPricingAndVol
WHERE (Symbol = @Ticker AND TradeDate <= @StartDate)
ORDER BY TradeDate DESC) AS T2
ORDER BY TradeDate ASC)
IF @DataPointDateFromTable = @TargetDate
SET @Result = 1
ELSE
SET @Result = 0
RETURN @Result
END
The query looks fine, problem could be on
dbo.TradingDateByStartDatefunction, check out if@DataPointDateFromTableand@TargetDateboth have the date and time part of their values, or if you van to compare only date parts, cast them to DATE as described here.