Suppose I have this sql statement and I executed the sql command to get the datareader:
"select 1 union select 2"
var rdr = cmd.ExecuteReader();
and now I want to read the value in the first column of the first row:
var myInt = (int)rdr.GetValue(0);
var myLong = (long)rdr.GetValue(0);
So, it looks like the type you are pointing to in C # should exactly match the SQL type. I.E. If the sql type is bigint, you can only use long ones. If the sql type is int, you can use only int. No mixing and matching ...
I just want to get something that works regardless of the C # integer type, and returns sql if you can theoretically drop one on top of the other. Therefore, if SQL Server gives me a floating point type, and I ask for an int, I want the truncated int you get from this cast.
My goal is to make this work with generics, so I can work with this function when the general parameter does not exactly match the data type in the SQL server:
List<T> GetFirstColumn<T>(string sql) where T : struct
{
}
I would like this to work for both entries:
var sql1 = "Select 1";
var sql2 = "Select cast(1 as bigint)";
var lst1 = GetFirstColumn<int>(sql1);
var lst2 = GetFirstColumn<int>(sql2);
Does anyone have a relatively painless way to do this?
source
share