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

前端 未结 5 1984
野性不改
野性不改 2020-12-31 21:45

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

相关标签:
5条回答
  • 2020-12-31 21:52

    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.

    0 讨论(0)
  • 2020-12-31 22:00

    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);
    
    0 讨论(0)
  • 2020-12-31 22:02

    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

    0 讨论(0)
  • 2020-12-31 22:12

    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"];
    
    0 讨论(0)
  • 2020-12-31 22:12

    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"
        }
    }
    
    0 讨论(0)
提交回复
热议问题