Below is a function, from what I can see there are no errors but when I attempt to build it I get the error "Could not find Stored Procedure ISDATE"
On a second note, if anyway has any better solution to my issue rather than my logic here, please let me know.
The requirement is to have a base day and to append that day every month to denote a range. The issue comes if the base day is 29, 30 or 31 and Feb rolls around, you will receive an error from SQL saying it is not a valid date. This functions purpose is to take three date parts and try and make a valid date to return.
CREATE FUNCTION Configuration.CreateDate
(
@Year INT,
@Month INT,
@Day INT
)
RETURNS DATE
AS
BEGIN
DECLARE @ReturnDate DATE
DECLARE @DateString varchar
DECLARE @VaildDate INT = 0;
WHILE @VaildDate = 0
BEGIN
SET @DateString = CAST(@Year AS VARCHAR(4)) + '-' +CAST(@Month AS VARCHAR(4)) + '-' + CAST(@Day AS VARCHAR(4))
IF ISDATE(@DateString) = 1
SET @ReturnDate = CAST(@DateString AS DATE)
SET @VaildDate = 1
ELSE
SET @Day = @Day - 1
END
RETURN @ReturnDate
END
GO
IF ISDATE(@DateString) = 1
to be replaced with:
IF TRY_CAST(@DateString AS DATE) IS NOT NULL
Adjusted DDL of the entire function:
CREATE FUNCTION Configuration.CreateDate
(
@Year INT,
@Month INT,
@Day INT
)
RETURNS DATE
AS
BEGIN
DECLARE @ReturnDate DATE
DECLARE @DateString varchar
DECLARE @VaildDate INT = 0;
WHILE @VaildDate = 0
BEGIN
SET @DateString = CAST(@Year AS VARCHAR(4)) + '-' +CAST(@Month AS VARCHAR(4)) + '-' + CAST(@Day AS VARCHAR(4))
IF TRY_CAST(@DateString AS DATE) IS NOT NULL
BEGIN
SET @ReturnDate = CAST(@DateString AS DATE)
SET @VaildDate = 1
END
ELSE
SET @Day = @Day - 1
END
RETURN @ReturnDate
END
On a second note, if anyway has any better solution to my issue rather than my logic here, please let me know.
Consider to not use scalar functions for such purposes at all. If such logic really needs to be encapsulated into some function, choose an inline type of UDF, but not a scalar one.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.