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

618 views Asked by At

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.

1

There are 1 answers

3
umberto-petrov On BEST ANSWER

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);
}