Link to home
Start Free TrialLog in
Avatar of BDPL
BDPLFlag for India

asked on

To get Column datatype from sqlserver table in C#-dotnet

Hi,
I have a table with 3 columns.

column   datatype
--------    -----------
x               int                with primary key
y               char(10)        
z              decimal(10,4)

I want to write a query, to get the particular column datatype  from this table, in C#-dotnet winforms application.

Plz, help on this
thanx.
ASKER CERTIFIED SOLUTION
Avatar of RiteshShah
RiteshShah
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
using System;
using System.Data;
using System.Data.SqlClient;


public class MainClass
{
    public static void Main()
    {
        SqlConnection thisConnection = new SqlConnection("server=(local)\\SQLEXPRESS;" + "integrated security=sspi;database=MyDatabase");
       
        //Sql Query 1
        string sql = "SELECT x,y,z FROM tablename; ";
       
        //Create Command object
        SqlCommand thisCommand = new SqlCommand(sql, thisConnection);
       
        try {
            // Open Connection
            thisConnection.Open();
            Console.WriteLine("Connection Opened");
           
            // Execute Query
            SqlDataReader thisReader = thisCommand.ExecuteReader();
           
            // Get column data types
            Console.WriteLine("Data types: {0} | {1}", thisReader.GetDataTypeName(0).PadLeft(13), thisReader.GetDataTypeName(1));
           
           
            //Close DataReader
               
            thisReader.Close();
        }
        catch (SqlException ex) {
            // Display error
            Console.WriteLine("Error: " + ex.ToString());
        }
        finally {
            // Close Connection
            thisConnection.Close();
               
            Console.WriteLine("Connection Closed");
        }
    }
}
well you can go for simple C# code also but my query is very simple and small, will give you all column name and datatype if you will just pass table name.
Avatar of BDPL

ASKER

Hi, thanx.
But i am not gettting datatype name. I got just datatype heading, in that no available names

plz..
Avatar of BDPL

ASKER

Hey,

Sorry

I got the exact output. Your qery is nice and simple.

thanx.
you can get more information about column as well, have a look at by SELECT *