简体   繁体   中英

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.

considering that you just have to check the datatypes of columns,if you want to get the column datatype in SQL database alone,you could use the query

SELECT COLUMN_NAME, DATA_TYPE 
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_NAME = 'yourTableName'

hope this helps.But this wont help in retrieving data and column datatype simultaneously.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM