Reputation: 55
I have searched around here and found some threads relating to this problem but they didn't helped me. I need to check the type of a SQL column in a certain datatable and compare it. So let's say I have a column called "CustomerName" and this is a varchar in SQL. Then I want to compare it with a string or something else which is "varchar" and check if this matches. For example it should fail when my column has the type numeric and the string the value "varchar". I think the case with the string is a bad idea (for example when I've got varchar(50) and compare it to "varchar"). Is there a way to do that?
Upvotes: 2
Views: 4558
Reputation: 10622
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)
}
else if (dataType == typeof(double))
{
// Do for doubles (DOUBLE, DECIMAL)
}
else if (dataType == typeof(string))
{
// Do for Strings (VARCHAR, NVARCHAR)
}
else if (dataType == typeof(DateTime))
{
// Do for DateTime (DATETIME)
}
else if (dataType == typeof(byte[]))
{
// Do for Binary (BINARY, VARBINARY, NVARBINARY, IMAGE)
}
}
}
Upvotes: 7
Reputation: 172608
You may try like this:
System.Type myType = reader.GetFieldType(value);
switch (myType.GetTypeCode(myType))
{
case TypeCode.String:
break;
// and so on ........
}
Upvotes: 0