sql server - passing unquoted constants to functions like DATEPART does

后端 未结 2 1303
终归单人心
终归单人心 2021-01-19 12:57

i would like to create a function which accepts a constant like the datepart function accepts yy/mm/dd/hh/

like:

select datepart(

相关标签:
2条回答
  • 2021-01-19 13:40

    You can't really constrain the input of a UDF to a small set of values (to the best of my knowledge).

    I would recommend creating a tabe for your enumerated values - something like this:

    CREATE TABLE MyEnumTable (DatePartID tinyint, DatePartValue char(2))
    GO
    INSERT MyEnumTable(DatePartID, DatePartValue)
    SELECT 1, 'yy'
    UNION
    SELECT 2, 'mm'
    UNION
    SELECT 3, 'dd'
    UNION
    SELECT 4, 'hh'
    GO
    
    CREATE FUNCTION MyDatePart(@IntervalType tinyint)
    RETURNS varchar(255)
    AS
    BEGIN
    IF NOT EXISTS (SELECT * FROM MyEnumTable WHERE DatePartID = @IntervalType)
       RETURN 'Invalid IntervalType'
    
    --Do your stuff
    DECLARE @DatePartvalue char(2)
    SELECT  @DatePartValue = DatePartValue
    FROM    MyEnumTable
    WHERE   DatePartID = @IntervalType
    
    RETURN @DatePartValue
    END
    
    GO
    
    --Check it out
    SELECT dbo.MyDatePart(3), dbo.MyDatePart(12)
    

    Of course, my example is oversimplified, but you get the idea.

    Also, consider making the function a table-valued function for performance reasons, if you're planning on using the udf in set statements. I blogged about the performance implications of various function types here:

    http://thehobt.blogspot.com/2009/02/scalar-functions-vs-table-valued.html

    0 讨论(0)
  • 2021-01-19 13:49

    i would like to create my own function that accepts dd not char like 'dd'

    I think you're out of luck on this. If you don't single-quote the characters, they'll be interpreted as a name--but you can't have defined them as a name anywhere if you want them to be used in the manner you propose.

    0 讨论(0)
提交回复
热议问题