我需要将DataTable添加到SQL查询中。
queryText = @"
WITH TaskDataTable AS
(
SELECT *
FROM @dataTable
)
INSERT INTO {0}.dbo.Tasks_Projects_PIR
...
FROM
TaskDataTable as TaskDataTable
LEFT JOIN dbo.MSP_EpmTask_UserView as t1
ON 1 = 1";
using (SqlCommand sqlCommand = new SqlCommand(queryText, ConfigurationProvider.sqlConnection))
{
sqlCommand.CommandType = CommandType.Text;
sqlCommand.Parameters.AddWithValue("eventUID", eventUid);
SqlParameter parameter = sqlCommand.Parameters.AddWithValue("@dataTable", dataTable);
parameter.TypeName = "dbo.Tasks_Projects_PIR";
parameter.SqlDbType = SqlDbType.Structured;
sqlCommand.ExecuteNonQuery();
}
DataTable创建代码:
DataTable myTvpTable = new DataTable("taskDataTable");
myTvpTable.Columns.Add("TaskUid", typeof(string));
myTvpTable.Columns.Add("TaskPredecessors", typeof(string));
myTvpTable.Columns.Add("TaskSuccessors", typeof(string));
foreach (ProjectDataSet.TaskRow taskRow in DataSetMaster.projectDS.Task)
{
var predecessors = string.Empty;
var successors = string.Empty;
PSIWorker.GetPredecessorsAndSuccessors(taskRow, out predecessors, out successors);
DataRow row = myTvpTable.NewRow();
row["TaskUid"] = taskRow.TASK_UID.ToString();
row["TaskPredecessors"] = predecessors;
row["TaskSuccessors"] = successors;
myTvpTable.Rows.Add(row);
}
我有下一个错误:
列,参数或变量@dataTable。 :找不到数据类型* dbo.Tasks_Projects_PIR。
或者,如果我没有设置parameter.TypeName
:
表格类型参数' dataTable'必须有一个有效的类型名称。
我可以使用DataTable作为参数吗?
答案 0 :(得分:0)
您需要在数据库中创建表类型:
CREATE TYPE [dbo].[TaskDataTable] AS TABLE
(
TaskUid varchar(20),
TaskPredecessors varchar(20)
)
在存储过程中使用上面的表类型:
create procedure [dbo].spEmptask
(
@taskTable TaskDataTable readonly
)
As
BEGIN
--your logic
END
C#代码:
using(SqlConnection con = new SqlConnection(connectionstring))
{
SqlCommand command = new SqlCommand("spEmptask",con);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("@taskTable", dt(your DataTable)));
}