Search code examples
sqlasp.net-mvcsql-trace

User-Defined Table Type insertion causing conversion error


Not a duplicate of User-Defined Table Type insertion sometimes causing conversion error

I have a user defined table type:

CREATE TYPE [dbo].[udtImport] AS TABLE(
    Name    varchar(256)    null
    Code    varchar(32) null
    StartDate   varchar(256)    null
    EndDate varchar(256)    null
    DateCreated datetime    null

The DateCreated field is populated in my DB layer using DateTime.Now(), while all other fields are from an imported table.

When I import a file with the date fields populated I get a SQL error:

Conversion failed when converting date and/or time from character string.

Intercepting the generated code using SQL Profiler shows this:

DECLARE @p1 dbo.udtImport;
INSERT INTO @p1
VALUES
  ( N'Kit A1', 
    N'A002',  
    '2016-04-02 00:00:00.000',
    '2016-10-10 00:01:00.000', 
    '2018-10-22 16:08:28.6823468' );

exec impSaveImport @ImportList=@p1

impSaveImport is a stored procedure that has just one parameter: the table type var and does a straight insert to table [Import]. No logic, no triggers, no reference to other tables.

Executing this code in SSMS shows the same error as expected.
Trimming the last 4 digits off the last DateTime field causes the insert query to succeed.

So far so good.

When I import a file with the StartDate and EndDate fields empty, I get no error, and data is successfully inserted into the Import table.

When I intercept the successful insert using profiler I get this:

DECLARE @p1 dbo.udtImport;
   INSERT INTO @p1
        VALUES
          ( N'Kit A1', 
            N'A002',  
            null,
            null, 
            '2018-10-22 16:34:11.5243245' );

        exec impSaveImport @ImportList=@p1

Keep in mind this query SUCCESSFULLY insert one row into the table Import.

When I run this latest query in SSMS I get the same conversion error as before,

but it ran without error from within my MVC app!

This last part has me stumped.

How can it be?

Project is using MVC with SQL2016.


Solution

  • You could use DATETIME2:

    CREATE TYPE [dbo].[udtImport] AS TABLE(
        Name    varchar(256)    null,
        Code    varchar(32) null,
        StartDate   varchar(256)    null,  -- should be datetime2 format
        EndDate varchar(256)    null,      -- should be datetime2 format
        DateCreated datetime2    null);
    
    DECLARE @p1 dbo.udtImport;
    INSERT INTO @p1(Name, Code, StartDate, EndDate, DateCreated)
    VALUES
      ( N'Kit A1', 
        N'A002',  
        '2016-04-02 00:00:00.000',
        '2016-10-10 00:01:00.000', 
        '2018-10-22 16:08:28.6823468' );
    

    db<>fiddle demo