我想調用一個存儲過程,它接受帶有一個字符串和一個日期時間列的表值參數。帶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