From within my C# app I'm calling a stored procedure using Dapper:
return conn.Query<MyList>("check_data", new { dataToCheck }, commandType: CommandType.StoredProcedure);
dataToCheck
is a DataTable
because check_data
accepts a TVP
. This table type has 2 columns (from_date varchar(20), to_date varchar(20)) and is based on the following class.
public class DataToCheckType
{
public DateTime? from_date {get; set;}
public DateTime? to_date {get; set;}
}
Dapper then sends the following to SQL Server:
declare @p1 dbo.CheckDataType
insert into @p1 values('2017-04-19 00:00:00','2017-04-19 00:00:00')
exec check_data @dataToCheck=@p1
The SP itself is simple. It calls a function that builds a SQL statement which is then executed:
DECLARE @sql nvarchar(max) = dbo.GetSql(@dataToCheck);
DECLARE @results TABLE (Id int);
INSERT INTO @results EXECUTE(@sql);
The GetSql
function starts like this:
DECLARE @fromDate datetime;
DECLARE @toDate datetime;
SELECT
@fromDate = CONVERT(datetime, from_date, 120),
@toDate = CONVERT(datetime, to_date, 120),
FROM
@dataToCheck;
And it continues building the SQL statement as expected. When running the SP
from T-SQL
everything works fine.
However, when running the same from code I get the following error:
check_data : 241 Conversion failed when converting date and/or time from character string
Why does the SP work in T-SQL but not when calling it from code? What is wrong with the dates?