2017-03-06 10 views
0

テーブル値パラメータを受け入れるストアドプロシージャを、1つの文字列と1つの日付時刻列で呼び出そうとしています。 PROCストアド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である必要があります。表値パラメータを送信するADO.Netを使用する場合

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

、データテーブルの列の順序は、正確ユーザー定義テーブル型の列の順序と一致する必要があります。それがバグか機能かどうかは分かりませんが、それはうまく機能しています。

はあなたのC#コードに次の2行の順序を切り替える必要があります。また

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; 
関連する問題