首页 > 解决方案 > 如何在 C# 中以结构化方式访问 SqlDbType 的 Sql 参数的列和数据?

问题描述

在 C# 中,对于表值参数,我添加了一个 SqlParameter,其中“SqlDbType”作为“Structured”,“Value”作为 C# DataTable。我想稍后在我的代码中提取这些数据。

  1. 我想验证 SqlDbType/DbType 是否为“结构化”。
  2. 如果是,并且“Value”是“DataTable”,我想获取其列的 columnNames 和 DataRows 中的数据。

下面是 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
}

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

标签: c#datatabletable-valued-parameterssqlparametersqldbtype

解决方案


我认为您可以简单地param.Value转换回 a 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);
}

推荐阅读