Can I create a One-Time-Use Function in a Script or Stored Procedure?

前端 未结 6 614
再見小時候
再見小時候 2020-12-24 11:04

In SQL Server 2005, is there a concept of a one-time-use, or local function declared inside of a SQL script or Stored Procedure? I\'d like to abstract away some complexity i

6条回答
  •  长发绾君心
    2020-12-24 11:56

    The below is what I have used i the past to accomplish the need for a Scalar UDF in MS SQL:

    IF OBJECT_ID('tempdb..##fn_Divide') IS NOT NULL DROP PROCEDURE ##fn_Divide
    GO
    CREATE PROCEDURE ##fn_Divide (@Numerator Real, @Denominator Real) AS
    BEGIN
        SELECT Division =
            CASE WHEN @Denominator != 0 AND @Denominator is NOT NULL AND  @Numerator != 0 AND @Numerator is NOT NULL THEN
            @Numerator / @Denominator
            ELSE
                0
            END
        RETURN
    END
    GO
    
    Exec ##fn_Divide 6,4
    

    This approach which uses a global variable for the PROCEDURE allows you to make use of the function not only in your scripts, but also in your Dynamic SQL needs.

提交回复
热议问题