2017-03-06 118 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; 
相關問題