Reputation: 3
I call a store procedure in C# the results are:
0.033333
0.550000
0.133333
24.133333
In my c# code I need to check which one is high than 24. How can I get double convert the query result to do that?
Here's my code:
sqlConnection con2 = conec.ObtenerCon();
SqlCommand com2 = new SqlCommand("ind_meta", con2);
com2.CommandType = System.Data.CommandType.StoredProcedure;
com2.Parameters.Add("@finicial", SqlDbType.DateTime);
com2.Parameters["@finicial"].Value = Convert.ToDateTime(fini + " " + hini);
com2.Parameters.Add("@ffinal", SqlDbType.DateTime);
com2.Parameters["@ffinal"].Value = Convert.ToDateTime(ffin + " " + hfin);
DataTable ds1 = new DataTable();
using (SqlDataAdapter a1 = new SqlDataAdapter(com2))
{
a1.Fill(ds1);
}
foreach (DataRow dsRow1 in ds1.Rows)
{
if (double.Parse(dsRow1[0].ToString(), NumberStyles.Currency) < 24)
a++;
if (double.Parse(dsRow1[0].ToString(), NumberStyles.Currency) > 24 &&
double.Parse(dsRow1.ToString(), NumberStyles.Currency) < 48)
b++;
if (double.Parse(dsRow1[0].ToString(), NumberStyles.Currency) > 48)
c++;
}
Upvotes: 0
Views: 1654
Reputation: 460148
I assume that you don't convert your double value to string in the database, so you don't need to convert it to string in C# neither. You just have to cast it accordingly.
double value = dsRow1.Field<double>(0);
So the complete loop:
foreach (DataRow dsRow1 in ds1.Rows)
{
double value = dsRow1.Field<double>(0);
if (value < 24)
a++;
else if (value >= 24 && value < 48)
b++;
else
c++;
}
Edit: "It doesn't work the error is about convert, the query is: datediff(date1,date2)/60"
DATEDIFF
has three arguments, so your code would even cause a syntax error. But i assume that you are using it with the datepart
argument, for example the hours:
DATEDIFF(hh, date1,date2)/60
This is an integer division since DATEDIFF
returns a signed integer. Integer divisions always result in an integer, the decimal part is truncated. You need to cast one side to a floating point number:
SELECT DATEDIFF(mi, GetDate(),DATEADD(dd,1,GetDate())) / CAST(60 AS DECIMAL(9,2))
Now you can cast it to decimal
:
foreach (DataRow dsRow1 in ds1.Rows)
{
decimal value = dsRow1.Field<decimal>(0);
if (value < 24)
a++;
else if (value >= 24 && value < 48)
b++;
else
c++;
}
However, why do you need to divide through 60 at all? That sounds as if you want to get the hours from minutes. Then you could use the correct datepart
in the first place:
DATEDIFF(hh, GetDate(),DATEADD(dd,1,GetDate()))
Upvotes: 1