SQLCLR and DateTime2

前端 未结 2 1943
孤街浪徒
孤街浪徒 2021-01-05 07:30

Using SQL Server 2008, Visual Studio 2005, .net 2.0 with SP2 (has support for new SQL Server 2008 data types).

I\'m trying to write an SQLCLR function that takes a D

2条回答
  •  走了就别回头了
    2021-01-05 07:57

    You need to change the DateTime types in the signature of your Function Method. SQLDateTime maps to a DateTime on the database.

    System.DateTime is more precise and can be mapped to DateTime2 (but by default, it'll be dropped as a DateTime in the deploy script).

    [SqlFunction(DataAccess = DataAccessKind.None)]
    //OLD Signature public static SqlDateTime UTCToLocalDT(SqlDateTime val) 
    public static DateTime UTCToLocalDT(DateTime val) {
       ...
    }
    

    Then you can tweak your deploy script to read.

    CREATE FUNCTION [UTCToLocalDT]
    (
        @dt [datetime2]
    )
    RETURNS [datetime2]
    AS
        EXTERNAL NAME [SQLCLR].[MyCompany.SQLCLR.DateTimeHelpCLR].UTCToLocalDT
    GO
    

    Running your function should now give you more precise output.

    DECLARE @input DateTime2, @output DateTime2
    SET @input = '2010-04-12 09:53:44.48123456'
    SET @output = YourDatabase.dbo.[UTCToLocalDT](@input)
    SELECT @input, @output
    

提交回复
热议问题