如何在 C# 中以结构化的形式访问 SqlDbType 的 Sql 参数的列和数据?

问题描述

在 C# 中,对于表值参数,我添加一个 sqlParameter,其中 'sqlDbType' 为 'Structured','Value' 为 C# DataTable。 我想稍后在我的代码提取这些数据。

  1. 我想验证 sqlDbType/DbType 是否为“结构化”。
  2. 如果是,并且“值”是“数据表”,我想获取其列的列名和数据行中的数据。

下面是sqlParameter的代码

DataTable memoIdDt = new DataTable();
sqlParameter param = new sqlParameter ("memos",sqlDbType.Structured) { Value = memoIdDt,TypeName = "Table_Type_In_DB" };

稍后我想做类似下面的事情(这不是确切的代码)。

//I am not able to use param.sqlDbType. I can use the param.DbType property.
//But it returns Object. So,not able to get the if clause right.
If(param.DbType == sqlDbType.Structued)
{
    //foreach column in param.Value.Columns,print columnNames
    //foreach DaTarow in param.Value,print the array
}

如果您知道如何实现这一点,请帮助。

解决方法

我认为您可以简单地将 param.Value 转换回 DataTable

if (param.SqlDbType == SqlDbType.Structured)
{
    var table = param.Value as DataTable;

    foreach (DataColumn column in table.Columns) Console.WriteLine(column.ColumnName);
    foreach (DataRow row in table.Rows) Console.WriteLine(row.ItemArray.Length);
}