我想调用一个存储过程,它接受带有一个字符串和一个日期时间列的表值参数。带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参数。但是添加额外的“名称”参数显然会导致一些问题。我究竟做错了什么?
我认为你必须创建一个类型= SqlDbType.Structured一个的SqlParameter并将它传递给您的存储过程 – PrfctByDsgn