简体   繁体   中英

How to access columns and data of a Sql parameter of SqlDbType as Structured in C#?

In C#, for Table-valued parameter I add a SqlParameter with 'SqlDbType' as 'Structured' and 'Value' as a C# DataTable. I want to extract this data later in my code.

  1. I want to verify if the SqlDbType/DbType is 'Structured'.
  2. If yes, and if the 'Value' is a 'DataTable', I want fetch the columnNames of its Columns and the data in the DataRows.

Below is the code for SqlParameter.

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

Later I want to do something like the below (this is not the exact code).

//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
}

Please help if you know how this can be achieved.

I think you can simply cast param.Value back to 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM