0

I have a SQL Server query; when I run it in SQL Server, it is returning the expected results, when I call the same query from C# code to fill a dataset, there are no results. What is the problem? My SQL query is as below along with results when run in SQL Server

SELECT 
    t0.brandID, t0.brandName, t0.cdt, t0.udt, t0.brandstatus, 
    t0.AddedBy  , 
    (SELECT 
         AVG(CAST(brandID AS bigint)) FROM brands) AS brandID_AVERAGE
FROM 
    brands t0 
WHERE  
    t0.cdt >= '2013-11-15 00:00:00' 
    AND t0.cdt <='2013-11-15 23:59:59' 
GROUP BY
    t0.brandID, t0.brandName, t0.cdt, t0.udt, t0.brandstatus, t0.AddedBy

and my results for the above query when run in SQL Server are :

brandID brandName   cdt udt brandstatus AddedBy brandID_AVERAGE
10  khasim  2013-11-15 19:14:18.123 2013-11-15 19:14:18.123 1   1   52778
11  khasim  2013-11-15 19:14:18.123 2013-11-15 19:14:18.123 1   1   52778
12  khasim  2013-11-15 19:14:18.123 2013-11-15 19:14:18.123 1   1   52778
13  khasim  2013-11-15 19:14:18.123 2013-11-15 19:14:18.123 1   1   52778
14  khasim  2013-11-15 19:14:18.123 2013-11-15 19:14:18.123 1   1   52778
15  khasim  2013-11-15 19:14:18.123 2013-11-15 19:14:18.123 1   1   52778
16  khasim  2013-11-15 19:14:18.123 2013-11-15 19:14:18.123 1   1   52778

But when I call the same thing from C# with command.Parameters.AddWithValue, my dataset is always null.

My c# code is

private void button1_Click(object sender, EventArgs e)
{
    checkedListBox1.Items.Clear();
    Cursor.Current = Cursors.WaitCursor;

    string QueryB=@"SELECT t0.brandID, t0.brandName, t0.cdt, t0.udt, 
        t0.brandstatus, t0.AddedBy, 
        ( SELECT  AVG( CAST (brandID AS bigint)) FROM brands ) 
          AS brandID_AVERAGE FROM brands t0 
             WHERE  t0.cdt >= @VALUE1 and  t0.cdt <=@VALUE2  
             group by t0.brandID,t0.brandName,t0.cdt,t0.udt,
                      t0.brandstatus,t0.AddedBy";

    if (textBox1.Text != string.Empty && textBox2.Text != string.Empty)
    {
        if (checkBox1.Checked == false)
        {
            try
            {
                if (QueryB != string.Empty)
                {
                    using (SqlConnection con = new SqlConnection(Properties.Settings.Default.connectionString))
                    {
                        con.Open();
                        SqlCommand cmd = new SqlCommand(QueryB, con);

                        if (checkBox6.Checked)
                        {
                            var sample1 = DateTime.ParseExact(textBox1.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd") + " " + dateTimePicker2.Value.ToString("HH:mm:ss tt");
                            var sample2 = DateTime.ParseExact(textBox2.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd") + " " + dateTimePicker1.Value.ToString("HH:mm:ss tt");

                            cmd.Parameters.AddWithValue("@Value1", sample1.ToString());
                            cmd.Parameters.AddWithValue("@Value2", sample2.ToString());
                        }
                        else
                        {
                            if (label2.Text.Contains("datetime"))
                            {
                                cmd.Parameters.AddWithValue("@Value1", DateTime.ParseExact(textBox1.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture).ToString("MM-dd-yyyy") + " " + "00:00:00.000");
                                cmd.Parameters.AddWithValue("@Value2", DateTime.ParseExact(textBox2.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture).ToString("MM-dd-yyyy") + " " + "23:59:59.999");
                            }
                            else
                            {
                                cmd.Parameters.AddWithValue("@Value1", textBox1.Text);
                                cmd.Parameters.AddWithValue("@Value2", textBox2.Text);
                            }
                        }

                        DataSet ds = new DataSet();

                        SqlDataAdapter da = new SqlDataAdapter(cmd);
                        cmd.ExecuteNonQuery();

                        da.Fill(ds);
                        con.Close();

                        dataGridView1.DataSource = ds.Tables[0];
                        mysource = ds.Tables[0];
                        dataGridView1.BindingContext = new BindingContext();
                        foreach (DataGridViewColumn col in dataGridView1.Columns)
                        {
                            checkedListBox1.Items.Add(col.HeaderText.ToString());

                        }
3
  • 2
    You probably need a hard coded single quote on the front and end of each date. like t0.cdt >= '@VALUE1' Commented Mar 21, 2016 at 23:15
  • 3
    Do not use AddWithValue, in particular when you want to pass a DateTime value Commented Mar 21, 2016 at 23:15
  • 2
    Can we stop using AddWithValue() already? Commented Mar 21, 2016 at 23:17

2 Answers 2

2

I am not sure about your query, but there is a very probable culprit in your code and it is the AddWithValue call together with a datetime parameter.

Your code transform the datetime value in a string and pass it to AddWithValue. This conversion happens using the rules of your locale settings.
AddWithValue has no clue about the fact that the underlying datatable column is a DateTime and thus creates a parameter of String type. At this point the parameters are passed to the database engine that need to re-convert the string value back to a DateTime. This conversion happens using the rules established for your database and probably an value is what cause your query to fail.

Just use the Add method specifying the exact datatype and let the database engine extract the value correctly from the parameter

cmd.Parameters.Add("@Value1", SqlDbType.DateTime).Value = sample1.Date; //2013/11/15 00:00:00
cmd.Parameters.Add("@Value2", SqlDbType.DateTime).Value = sample2.AddSeconds(86339); // 2013/11/15 23:59:59
Sign up to request clarification or add additional context in comments.

3 Comments

i changed it to the way you suggested but still the same
Probably because the two datetime represent the same point in time and you need a whole day. Changed a bit the answer above
i understood the problem i am using date and time as 15/11/2013 00:00:00 AM which is ok 15/11/2013 24:00:00 which is not there sql server has 15/11/2013 23:59:59.999 this is changing to next day but my query is not converting to date or time format causing the problem.
0

I think you need to replace cmd.ExecuteNonQuery(); with cmd.ExecuteReader()

though i have no way of testing

1 Comment

You could try pulling out the data adapter and just try executing the reader, maybe narrow things down. So sorry to not be of more help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.