Search code examples
c#sql-server-2008-r2sqldatatypesdatacolumn

How are database datatypes returned in DataColumn class?


I have searched and found surprisingly few results. I found that there is some datatype property for DataColums, but when retrieving data from a SQL server database, what is the datatype of whatever is retrieved? I'm working with a SqlDataAdapter to fill a DataTable. To get the values, I work as follows:

DataTable dtt = Database.get(SQLString); //pseudo-code
string value = dtt.Rows[0][0]; //Or is this a string?

So what is in dtt.Rows[0][0] if the database column datatype is bigint, int, date or bit? Do I need to convert them to string first and then convert them to other datatypes I require?


Solution

  • Well it depends how is defined in database, for example let's say that you have this table :

    CREATE TABLE [dbo].[Test](
        [ID] [int] NOT NULL,
        [Name] [nvarchar](128) NOT NULL,
        [Birthday] [datetime]) 
    

    then you can access first row like that :

    DataTable dtt = Database.get("Select * from Test"); //pseudo-code
    DataRow rw = dtt.Rows[0];
    int id = rw.Field<int>("ID");
    string name = rw.Field<string>("Name");
    DateTime dt = rw.Field<DateTime>("Birthday");
    

    or

    DataTable dtt = Database.get("Select * from Test"); //pseudo-code
    int id = (int) dtt[0]["ID"];
    string name = (string) dtt[0]["Name"];
    DateTime dt = (DateTime) dtt[0]["Birthday")];