Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the SqlDbType of a column in a table using ADO.NET?

I'm trying to determine at runtime what the SqlDbType of a sql server table column is.

is there a class that can do that in System.Data.SqlClient or should I do the mapping myself? I can get a string representation back from

SELECT DATA_TYPE, CHARACTER_MAXIMUM_LENGTH
FROM INFORMATION_SCHEMA.COLUMNS
   WHERE TABLE_CATALOG = '{0}' AND TABLE_SCHEMA = '{1}' 
   AND TABLE_NAME = '{2}' AND COLUMN_NAME = '{3}'

EDIT: I can't use SMO as I have no control over the executing machine so I can't guarantee it will be installed. (Sorry for not making that clear rp).

EDIT: In answer to Joel, I'm trying to make a function that I can call that will return me a SqlDBType when passed a SqlConnection, a table name, and a column name.

like image 289
WOPR Avatar asked Jan 19 '09 23:01

WOPR


People also ask

What is SqlDbType?

SqlDbType: It is used to set the SQL Server Datatypes for a given parameter. ParameterName: It is used to specify a parameter name. Direction: It is used for setting the direction of a SqlParameter. It is Input or Output or both (InputOutput). Size: It is used to set the maximum size of the value of the parameter.

What is SqlDbType structured?

The SqlDbType property of the SqlParameter is set to Structured . The AddWithValue passes the OracleDataReader result set to the stored procedure as a table-valued parameter. C# Copy. // Assumes connection is an open SqlConnection.

How many types of data table are in SQL Net?

1 Answer. There are three types of tables in SQL such as base, view, and merged. The data in these tables has different properties from other tables.


1 Answers

In SQL Server you can use the FMTONLY option. It allows you to run a query without getting any data, just returning the columns.

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 162
Adam Ruth Avatar answered Oct 21 '22 07:10

Adam Ruth