You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

为SQL Server 2014自定义函数添加错误处理提示

Adding Error Handling to Your SQL Server 2014 Scalar Function

Great question—let's beef up your jdate_practice function with proper error handling to catch invalid parameters and unexpected issues, while keeping your core calculation logic intact. Here's a modified version that includes validation and clear error messaging:

CREATE OR ALTER FUNCTION [dbo].[jdate_practice] (@p1 INT, @p2 CHAR(8)) 
RETURNS INT 
AS 
BEGIN
    DECLARE @v2 DATETIME, @result INT

    BEGIN TRY
        -- Validate @p1 is a reasonable fiscal year (adjust range to match your needs)
        IF @p1 < 1900 OR @p1 > 2100
            THROW 50001, '@p1 must be a valid year between 1900 and 2100', 1;

        -- Validate @p2 is a valid YYYYMMDD date string
        IF ISDATE(@p2) = 0
            THROW 50002, '@p2 must be a valid date in YYYYMMDD format (e.g., ''20180701'')', 1;

        -- Execute core calculation logic
        SET @v2 = CAST(@p2 AS DATETIME)
        SET @result = ((DATEPART(yyyy, @v2) * 12) + DATEPART(mm, @v2)) - ((@p1 * 12) + 6)

        RETURN @result
    END TRY
    BEGIN CATCH
        -- Re-throw the error to pass the detailed message back to the caller
        THROW;
        
        -- Optional: If you prefer returning an error code instead of throwing, use this instead:
        -- RETURN -999; -- Use a unique sentinel value to signal an error in calling queries
    END CATCH
END

Key Error Handling Features Explained:

  • Explicit Parameter Validation:

    • We first check that @p1 falls within a realistic year range (1900-2100 here—tweak this to match your fiscal year requirements). If not, we throw a custom error with a clear message.
    • We use ISDATE(@p2) to ensure the input string is a valid date in the required 8-character YYYYMMDD format. This catches malformed dates like '20181301' (invalid month) or '20180732' (invalid day).
  • TRY/CATCH Block:

    • The core logic lives inside a TRY block. Any unexpected errors (like conversion failures that slip past validation, or arithmetic overflow) will trigger the CATCH block.
    • In the CATCH block, THROW; re-raises the original error so the caller gets the exact issue details. If you'd rather have the function return a value instead of throwing an error, comment out THROW; and uncomment the RETURN -999; line—just make sure your calling code checks for this sentinel value.

Test Cases to Verify:

  • Valid Input: SELECT dbo.jdate_practice(2018, '20180701') still returns 1 as expected.
  • Invalid Year: SELECT dbo.jdate_practice(1899, '20180701') throws:
    Msg 50001, Level 16, State 1, Line 1 @p1 must be a valid year between 1900 and 2100
  • Invalid Date Format: SELECT dbo.jdate_practice(2018, '20181301') throws:
    Msg 50002, Level 16, State 1, Line 1 @p2 must be a valid date in YYYYMMDD format (e.g., '20180701')

内容的提问来源于stack exchange,提问作者QuickLearner

火山引擎 最新活动