Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the SqlType of a column in a DataTable?

Tags:

I have a DataTable obtained from a SQL DataBase, like this:

using (SqlCommand cmd = new SqlCommand(query, _sqlserverDB)) {     using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))     {         DataSet dataSet = new DataSet();         adapter.Fill(dataSet);         result = (dataSet != null && dataSet.Tables != null && dataSet.Tables.Count > 0) ? dataSet.Tables[0] : null;     } } 

When I try to get the DataType of each column through dataColumn.DataType , I get the C# types (Int32, Int64, String, etc).

QUESTION: How can I access the native SQL data types (varchar, nvarchar, bigint...) instead of the C# types?

I have tried dataColumn.DataType.UnderlyingSystemType and the result is the same.

like image 273
DarthRoman Avatar asked Sep 19 '11 11:09

DarthRoman


People also ask

How can I get specific column from DataTable?

The DataTables columns() and column() (also optionally cells() and cell() ) methods provide the ability to select columns from the table. Which columns are selected and how the selector actually operates is controlled by this column-selector data type.

How do you check if a column has a DataTable?

You can use operator Contains , private void ContainColumn(string columnName, DataTable table) { DataColumnCollection columns = table. Columns; if (columns. Contains(columnName)) { .... } }


2 Answers

Of course it is possible to take SqlDbType of a column, the answer is here on SO: link.

SqlCommand cmd = connection.CreateCommand(); cmd.CommandText = "SET FMTONLY ON; select column from table; SET FMTONLY OFF"; SqlDataReader reader = cmd.ExecuteReader(); SqlDbType type = (SqlDbType)(int)reader.GetSchemaTable().Rows[0]["ProviderType"]; 
like image 109
infografnet Avatar answered Sep 19 '22 18:09

infografnet


You cannot because System.Data.DataTable (or DataColumn, or DataSet, or DataRow...) is a generic .NET data container which works the same way regardless on the specific database engine you loaded your data from.

this means that provided you used a .NET Connector for SQL Server, MySQL, Access, PostgreSQL or anything else, the DataTable and DataColumn classes are always the same and being ADO.NET objects are generic to work with any db engine, so the columns are typed with the .NET types as you have found out.

like image 35
Davide Piras Avatar answered Sep 20 '22 18:09

Davide Piras