Search code examples
c#sql-servertypesdatareader

SqlDataReader doesn't read when column empty


I have a problem with the following code:

public void checkTypes(String sqlTable, String sqlColumn)
{
    using (SqlConnection connection = new       SqlConnection(conStr.Text))
    {
        String query = "SELECT " + sqlColumn + " FROM " + sqlTable;

        SqlCommand command = new SqlCommand(query, connection);

        connection.Open();
        SqlDataReader read = command.ExecuteReader();

        while (read.Read())
        {
            for (int i = 0; i < read.FieldCount; i++)
            {
                Type dataType = read.GetFieldType(i);

                if (dataType == typeof(int))
                {
                    // Do for integers (INT, SMALLINT, BIGINT)
                    typeOf = "Integer";
                    read.Close();
                    connection.Close();
                    return;
                }
                else if (dataType == typeof(double))
                {
                     //and so on...
                }
            }
        }
    }
}

Now... I just want to check the types of my columns but the problem is that when the table gets created it has no entries and then the while loop does not get entered at all. How can I modify this slightly without writing completely new code? I don't want to insert pseudo values. Thank you! Hope someone can help me.

EDIT:

Ok so I explain a little bit more: The user can enter column names in different textboxes. Now I want to take the column name from each box and check if the datatype matches the datatype the column should have.


Solution

  • Akhil beat me to it but I would expand it to

    SELECT COLUMN_NAME, DATA_TYPE
    FROM information_schema.columns
    WHERE table_name = 'tableName' AND column_name = 'columnName'
    

    since you have the column names and the table name already