我正在尝试运行一个测试用例,但这根本行不通... 我在这里做错了什么?
这是 SQL:
CREATE TABLE
Playground.Test (saved DateTime)
GO
CREATE TYPE
Playground.DateTimeTable AS TABLE
([time] DATETIME);
GO
CREATE PROCEDURE
Playground.InsertDate
@dt Playground.DateTimeTable READONLY
AS
BEGIN
INSERT INTO Playground.Test (saved)
SELECT [time]
FROM @dt
END
GO
连接和执行程序的代码:
const String connString =
"server = SERVER; database = DB; UID = myUserID; pwd = myPassword;";
static void Main(string[] args)
{
SqlCommand command =
new SqlCommand(
"EXEC Playground.InsertDate",
new SqlConnection(connString));
DataTable table = new DataTable("DateTimeTable");
table.Columns.Add("[time]", typeof(DateTime));
table.Rows.Add(DateTime.Parse("10/27/2004"));
SqlParameter tvp = command.Parameters.AddWithValue("@dt", table);
tvp.SqlDbType = SqlDbType.Structured;
tvp.TypeName = "Playground.DateTimeTable";
command.Connection.Open();
int affected = command.ExecuteNonQuery();
command.Connection.Close();
Console.WriteLine(affected);
Console.ReadKey();
}
我没有收到任何错误。只有 0 行受影响。
虽然这在 SQL Server 中有效:
DECLARE @dt Playground.DateTimeTable
INSERT INTO @dt VALUES ('2004-10-27')
EXEC Playground.InsertDate @dt
我应该在这里做什么?
最佳答案
您没有将 SqlCommand
对象设置为存储过程。你应该做几件事:
- 从字符串中删除
EXEC
前缀 ~(不需要) 将
command
设置为存储过程:command.CommandType = CommandType.StoredProcedure;
- 也不确定
DataTable
列名称周围的方括号对此有何影响,但我怀疑删除它们会更好。
关于C# 将表值参数传递给 SqlCommand 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30600117/