简体   繁体   中英

Datetime type mismatch trying to publish a SQL CLR database

I'm trying to stand up an old solution that's publishing a number of .net functions to a SQL Server database. But the attempt to publish to a new database is failing on a function that manipulates dates.

The function that's failing is:

[SqlFunction(TableDefinition="localtime datetime2", IsDeterministic=true, IsPrecise=true,
             DataAccess=DataAccessKind.None,
             SystemDataAccess=SystemDataAccessKind.None)]
public static DateTime ConvertFromUTC(DateTime utctime, string timezoneid)
{
    if (utctime.Kind == DateTimeKind.Unspecified)
        utctime = DateTime.SpecifyKind( utctime, DateTimeKind.Utc );

    utctime = utctime.ToUniversalTime();

    return TimeZoneInfo.ConvertTimeBySystemTimeZoneId( utctime, timezoneid );
}

The error message I get when attempting to publish is:

Creating [dbo].[ConvertFromUTC]...

(268,1): SQL72014: .Net SqlClient Data Provider:

Msg 6551, Level 16, State 2, Procedure ConvertFromUTC, Line 1
CREATE FUNCTION for "ConvertFromUTC" failed because T-SQL and CLR types for return value do not match.

(268,0): SQL72045: Script execution error

SQL generated from the .net in an attempt to add the function:

CREATE FUNCTION [dbo].[ConvertFromUTC]
    (@utctime DATETIME, @timezoneid NVARCHAR (MAX))
RETURNS TABLE ([localtime] DATETIME2 (7) NULL)
AS EXTERNAL NAME [database].[IntelligentTutor.Database.Functions].[ConvertFromUTC]

SQL definition for the version of the function in the existing database (which confirms that @MattJohnson was right about how it needs fixed):

CREATE FUNCTION [dbo].[ConvertFromUTC]
    (@utctime [datetime], @timezoneid [nvarchar](4000))
RETURNS [datetime] WITH EXECUTE AS CALLER
AS EXTERNAL NAME [database].[IntelligentTutor.Database.Functions].[ConvertFromUTC]

The SQL function doesn't match the .NET method signature. To make it match:

  1. Change your the type of @utctime to DATETIME2 instead of DATETIME in the function definition.

  2. Change the return type to just RETURNS DATETIME2 instead of returning a table with a nullable datetime2 column.

Also, note that if you are on SQL 2016 or later, or on Azure SQL DB, you don't need this function, as you can now use AT TIME ZONE instead.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM