2017-03-06 1 views
0

하나의 문자열과 날짜 시간 열이있는 테이블 값 매개 변수를 허용하는 저장 프로 시저를 호출하려고합니다. 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# 코드에서 다음 두 행의 순서를 전환해야합니다 또한

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; 
관련 문제