2017-03-06 113 views
0

我想调用一个存储过程,它接受带有一个字符串和一个日期时间列的表值参数。带DateTime列的DataTable抛出“转换日期和/或时间时转换失败”

存储过程

ALTER PROCEDURE [dbo].[uspStoredProcedureDateTimeTableValueTest] 
-- Add the parameters for the stored procedure here 
@Param DateTimeType READONLY 
AS 
BEGIN 
    -- SET NOCOUNT ON added to prevent extra result sets from 
    -- interfering with SELECT statements. 
    SET NOCOUNT ON; 


END 

TVP:

CREATE TYPE DateTimeType AS TABLE 
(
    Name nvarchar(50), 
    ModifiedDate datetime 
) 

.NET控制台应用程序:

static void Main(string[] args) 
    { 
     string connectionString = ConfigurationManager.ConnectionStrings["default"].ConnectionString; 
     using (SqlConnection connection = new SqlConnection(connectionString)) 
     { 
      connection.Open(); 

      DataTable table = new DataTable("Test"); 
      table.Columns.Add("ModifiedDate", typeof(DateTime)); 
      table.Columns.Add("Name", typeof(string)); 

      DataRow row = table.NewRow(); 
      row["Name"] = "David"; 
      row["ModifiedDate"] = DateTime.Now; 
      table.Rows.Add(row); 

      SqlCommand command = new SqlCommand("uspStoredProcedureDateTimeTableValueTest", connection); 
      command.CommandType = CommandType.StoredProcedure; 
      command.Parameters.AddWithValue("@Param", table); 

      command.ExecuteNonQuery(); 
     } 
    } 

每当我试着执行从.NET我得到一个错误此SP:

An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll

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

The data for table-valued parameter "@Param" doesn't conform to the table type of the parameter. SQL Server error is: 241, state: 1

The statement has been terminated.

它似乎工作时,我只有DateTime参数。但是添加额外的“名称”参数显然会导致一些问题。我究竟做错了什么?

+0

我认为你必须创建一个类型= SqlDbType.Structured一个的SqlParameter并将它传递给您的存储过程 – PrfctByDsgn

回答

1

你错过了一个关键的事情。您添加到命令中的参数必须为SqlDbType.Structured

var param = new SqlParameter(); 
param.ParameterName= "@Param"; 
param.SqlDbType = System.Data.SqlDbType.Structured; 
param.Value = table; 
command.Parameters.Add(param); 
0

当使用ADO.Net发送表值参数,该数据表的列的顺序必须与用户定义的表类型的列的顺序相匹配。我不知道这是一个错误还是一个功能,但这就是它的工作原理。

你需要切换在C#代码后两排的顺序:

table.Columns.Add("ModifiedDate", typeof(DateTime)); 
table.Columns.Add("Name", typeof(string)); 

此外,Do not use AddWithValue。相反,使用Add

command.Parameters.Add("@Param", SqlDbType.Structured).Value = table; 
相关问题