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
You can use enum System.Data.CommandBehavior as paramter for method SqlCommand.ExecuteReader(System.Data.CommandBehavior.KeyInfo):
SqlCommand cmd = connection.CreateCommand();
cmd.CommandText = "select column from table";
SqlDataReader reader = cmd.ExecuteReader(System.Data.CommandBehavior.KeyInfo);
SqlDbType type = (SqlDbType)(int)reader.GetSchemaTable().Rows[0]["ProviderType"];
This example looks like the example with using sql: SET FMTONLY ON; SET FMTONLY OFF. But you haven't to use SET FMTONLY. And in this case you don't
receive data from the table. You receive only metadata.
Old question, but if all you are trying to do is get from the string DATA_TYPE to the SqlDbType enum, the query presented in the original question combined with one line of code will do the trick:
string dataType = "nvarchar"; // result of the query in the original question
var sqlType = (SqlDbType)Enum.Parse(typeof(SqlDbType), dataType, true);
For SQL Server, use the SMO (SQL Server Management Objects).
http://www.yukonxml.com/articles/smo/
For example, you can use this code to traverse over all of the columns of a table.
Server server = new Server();
Database database = new Database( "MyDB" );
Table table = new Table( database, "MyTable" );
foreach ( Column column in table.Columns )
{
WriteLine( column.Name );
}
Here are all of the column properties available to you: http://msdn.microsoft.com/en-us/library/microsoft.sqlserver.management.smo.column_members.aspx
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"];
If you are eventually going to read the data, you can do this:
SqlCommand comm = new SqlCommand("SELECT * FROM Products", connection);
using (SqlDataReader reader = comm.ExecuteReader())
{
while (reader.Read())
{
Type type = reader.GetSqlValue(0).GetType();
// OR Type type = reader.GetSqlValue("name").GetType();
// yields type "System.Data.SqlTypes.SqlInt32"
}
}