SQL Server 2005 query works in SQL Server Management Studio Express but not in Delphi 2010









up vote
1
down vote

favorite












I'm using SQL Server 2005 Management Studio Express and Delphi 2010. Fecha_hora = Date_Time is smalldatetime.



My date format is dd/mm/yyy



The dates in my table are saved like this:



08/01/2013 11:22:00 a.m.


I have this query in Delphi to know at which hours the sales are higher given a period of time; days/months, in this case I'm testing with the same day 8 Jan 2013:



 conect.Q_total_hora.Active:=false;
conect.Q_total_hora.SQL.Clear;
conect.Q_total_hora.SQL.Add('select datepart(hh, fecha_hora) as Hora, sum(Total) as Venta, a.tipo as Tipo');
conect.Q_total_hora.SQL.Add('from ventas v join articulos a on v.id_articulo=a.id_articulo');
conect.Q_total_hora.SQL.Add('where tipo='+char(39)+DBLUCB_tipo.Text+char(39)+' and cast(Convert(varchar(10), fecha_hora, 112) as datetime) between'+char(39)+DateToStr(DateTimePicker_fecha1.Date)+char(39)+ 'and'+char(39)+DateToStr(DateTimePicker_fecha2.Date)+char(39));
conect.Q_total_hora.SQL.Add('group by datepart(hh,fecha_hora), a.tipo order by datepart(hh,fecha_hora) ');
conect.Q_total_hora.Active:=true;


I use cast(Convert(varchar(10), fecha_hora, 112) as datetime) because I found on the internet that this way I can retrieve only the date without the time to retrieve data between dates.



In the DateTimePickers I choose 08/01/2013 as 8 Jan 2013



I used a memo to see the query memo1.Text:=conect.Q_total_hora.Text;



and the query I receive is:



select datepart(hh, fecha_hora) as Hora, sum(Total) as Venta, a.tipo as Tipo
from ventas v join articulos a on v.id_articulo=a.id_articulo
where tipo='Burrito Grande' and cast(Convert(varchar(10), fecha_hora, 112) as datetime) between'08/01/2013'and'08/01/2013'
group by datepart(hh,fecha_hora), a.tipo order by datepart(hh,fecha_hora)


The problem I have is that when I run this query in SQL Server Mgmt Studio, it returns values, but not in Delphi, and in Delphi if i set the values of the DateTimePickers to 01/08/2013 as 1 Aug 2013 it returns the values of 08/01/2012.



As far as I know (and I don't know much...) when I send a query to SQL Server it is like if I'm writing it in SQL... why if I'm sending the date 08/01/2013 as a string it doesn't return anything?



Thank you in advance. I'm not good in database, most things I look for them on the internet ^^










share|improve this question



















  • 2




    BETWEEN is terrible for this, as is converting to a string to get rid of time. Try WHERE fecha_hora >= '20130801' AND fecha_hora < '20130802'... see sqlblog.com/blogs/aaron_bertrand/archive/2011/10/19/…, sqlperformance.com/2012/09/t-sql-queries/… and sqlperformance.com/2012/10/t-sql-queries/trim-time
    – Aaron Bertrand
    Jan 9 '13 at 1:27







  • 3




    What happens if someone enters Jose's Burrito for DBLUCB_tipo? (or creates a tipo with an apostrophe). This will lead to SQL syntax error. Parameterized queries will also avoid this problem! See also bobby-tables.com/delphi.html
    – Gerry Coll
    Jan 9 '13 at 5:19











  • @AaronBertrand I changed the way i deal with dates to yours, and it worked great, it might have not solved my question of why the code runs in SQL and not in delphi but it solved my problem and showed me a better way to use dates. Could you change it to an answere so i can set it as the answere?
    – Edgar Holguin
    Jan 10 '13 at 17:43














up vote
1
down vote

favorite












I'm using SQL Server 2005 Management Studio Express and Delphi 2010. Fecha_hora = Date_Time is smalldatetime.



My date format is dd/mm/yyy



The dates in my table are saved like this:



08/01/2013 11:22:00 a.m.


I have this query in Delphi to know at which hours the sales are higher given a period of time; days/months, in this case I'm testing with the same day 8 Jan 2013:



 conect.Q_total_hora.Active:=false;
conect.Q_total_hora.SQL.Clear;
conect.Q_total_hora.SQL.Add('select datepart(hh, fecha_hora) as Hora, sum(Total) as Venta, a.tipo as Tipo');
conect.Q_total_hora.SQL.Add('from ventas v join articulos a on v.id_articulo=a.id_articulo');
conect.Q_total_hora.SQL.Add('where tipo='+char(39)+DBLUCB_tipo.Text+char(39)+' and cast(Convert(varchar(10), fecha_hora, 112) as datetime) between'+char(39)+DateToStr(DateTimePicker_fecha1.Date)+char(39)+ 'and'+char(39)+DateToStr(DateTimePicker_fecha2.Date)+char(39));
conect.Q_total_hora.SQL.Add('group by datepart(hh,fecha_hora), a.tipo order by datepart(hh,fecha_hora) ');
conect.Q_total_hora.Active:=true;


I use cast(Convert(varchar(10), fecha_hora, 112) as datetime) because I found on the internet that this way I can retrieve only the date without the time to retrieve data between dates.



In the DateTimePickers I choose 08/01/2013 as 8 Jan 2013



I used a memo to see the query memo1.Text:=conect.Q_total_hora.Text;



and the query I receive is:



select datepart(hh, fecha_hora) as Hora, sum(Total) as Venta, a.tipo as Tipo
from ventas v join articulos a on v.id_articulo=a.id_articulo
where tipo='Burrito Grande' and cast(Convert(varchar(10), fecha_hora, 112) as datetime) between'08/01/2013'and'08/01/2013'
group by datepart(hh,fecha_hora), a.tipo order by datepart(hh,fecha_hora)


The problem I have is that when I run this query in SQL Server Mgmt Studio, it returns values, but not in Delphi, and in Delphi if i set the values of the DateTimePickers to 01/08/2013 as 1 Aug 2013 it returns the values of 08/01/2012.



As far as I know (and I don't know much...) when I send a query to SQL Server it is like if I'm writing it in SQL... why if I'm sending the date 08/01/2013 as a string it doesn't return anything?



Thank you in advance. I'm not good in database, most things I look for them on the internet ^^










share|improve this question



















  • 2




    BETWEEN is terrible for this, as is converting to a string to get rid of time. Try WHERE fecha_hora >= '20130801' AND fecha_hora < '20130802'... see sqlblog.com/blogs/aaron_bertrand/archive/2011/10/19/…, sqlperformance.com/2012/09/t-sql-queries/… and sqlperformance.com/2012/10/t-sql-queries/trim-time
    – Aaron Bertrand
    Jan 9 '13 at 1:27







  • 3




    What happens if someone enters Jose's Burrito for DBLUCB_tipo? (or creates a tipo with an apostrophe). This will lead to SQL syntax error. Parameterized queries will also avoid this problem! See also bobby-tables.com/delphi.html
    – Gerry Coll
    Jan 9 '13 at 5:19











  • @AaronBertrand I changed the way i deal with dates to yours, and it worked great, it might have not solved my question of why the code runs in SQL and not in delphi but it solved my problem and showed me a better way to use dates. Could you change it to an answere so i can set it as the answere?
    – Edgar Holguin
    Jan 10 '13 at 17:43












up vote
1
down vote

favorite









up vote
1
down vote

favorite











I'm using SQL Server 2005 Management Studio Express and Delphi 2010. Fecha_hora = Date_Time is smalldatetime.



My date format is dd/mm/yyy



The dates in my table are saved like this:



08/01/2013 11:22:00 a.m.


I have this query in Delphi to know at which hours the sales are higher given a period of time; days/months, in this case I'm testing with the same day 8 Jan 2013:



 conect.Q_total_hora.Active:=false;
conect.Q_total_hora.SQL.Clear;
conect.Q_total_hora.SQL.Add('select datepart(hh, fecha_hora) as Hora, sum(Total) as Venta, a.tipo as Tipo');
conect.Q_total_hora.SQL.Add('from ventas v join articulos a on v.id_articulo=a.id_articulo');
conect.Q_total_hora.SQL.Add('where tipo='+char(39)+DBLUCB_tipo.Text+char(39)+' and cast(Convert(varchar(10), fecha_hora, 112) as datetime) between'+char(39)+DateToStr(DateTimePicker_fecha1.Date)+char(39)+ 'and'+char(39)+DateToStr(DateTimePicker_fecha2.Date)+char(39));
conect.Q_total_hora.SQL.Add('group by datepart(hh,fecha_hora), a.tipo order by datepart(hh,fecha_hora) ');
conect.Q_total_hora.Active:=true;


I use cast(Convert(varchar(10), fecha_hora, 112) as datetime) because I found on the internet that this way I can retrieve only the date without the time to retrieve data between dates.



In the DateTimePickers I choose 08/01/2013 as 8 Jan 2013



I used a memo to see the query memo1.Text:=conect.Q_total_hora.Text;



and the query I receive is:



select datepart(hh, fecha_hora) as Hora, sum(Total) as Venta, a.tipo as Tipo
from ventas v join articulos a on v.id_articulo=a.id_articulo
where tipo='Burrito Grande' and cast(Convert(varchar(10), fecha_hora, 112) as datetime) between'08/01/2013'and'08/01/2013'
group by datepart(hh,fecha_hora), a.tipo order by datepart(hh,fecha_hora)


The problem I have is that when I run this query in SQL Server Mgmt Studio, it returns values, but not in Delphi, and in Delphi if i set the values of the DateTimePickers to 01/08/2013 as 1 Aug 2013 it returns the values of 08/01/2012.



As far as I know (and I don't know much...) when I send a query to SQL Server it is like if I'm writing it in SQL... why if I'm sending the date 08/01/2013 as a string it doesn't return anything?



Thank you in advance. I'm not good in database, most things I look for them on the internet ^^










share|improve this question















I'm using SQL Server 2005 Management Studio Express and Delphi 2010. Fecha_hora = Date_Time is smalldatetime.



My date format is dd/mm/yyy



The dates in my table are saved like this:



08/01/2013 11:22:00 a.m.


I have this query in Delphi to know at which hours the sales are higher given a period of time; days/months, in this case I'm testing with the same day 8 Jan 2013:



 conect.Q_total_hora.Active:=false;
conect.Q_total_hora.SQL.Clear;
conect.Q_total_hora.SQL.Add('select datepart(hh, fecha_hora) as Hora, sum(Total) as Venta, a.tipo as Tipo');
conect.Q_total_hora.SQL.Add('from ventas v join articulos a on v.id_articulo=a.id_articulo');
conect.Q_total_hora.SQL.Add('where tipo='+char(39)+DBLUCB_tipo.Text+char(39)+' and cast(Convert(varchar(10), fecha_hora, 112) as datetime) between'+char(39)+DateToStr(DateTimePicker_fecha1.Date)+char(39)+ 'and'+char(39)+DateToStr(DateTimePicker_fecha2.Date)+char(39));
conect.Q_total_hora.SQL.Add('group by datepart(hh,fecha_hora), a.tipo order by datepart(hh,fecha_hora) ');
conect.Q_total_hora.Active:=true;


I use cast(Convert(varchar(10), fecha_hora, 112) as datetime) because I found on the internet that this way I can retrieve only the date without the time to retrieve data between dates.



In the DateTimePickers I choose 08/01/2013 as 8 Jan 2013



I used a memo to see the query memo1.Text:=conect.Q_total_hora.Text;



and the query I receive is:



select datepart(hh, fecha_hora) as Hora, sum(Total) as Venta, a.tipo as Tipo
from ventas v join articulos a on v.id_articulo=a.id_articulo
where tipo='Burrito Grande' and cast(Convert(varchar(10), fecha_hora, 112) as datetime) between'08/01/2013'and'08/01/2013'
group by datepart(hh,fecha_hora), a.tipo order by datepart(hh,fecha_hora)


The problem I have is that when I run this query in SQL Server Mgmt Studio, it returns values, but not in Delphi, and in Delphi if i set the values of the DateTimePickers to 01/08/2013 as 1 Aug 2013 it returns the values of 08/01/2012.



As far as I know (and I don't know much...) when I send a query to SQL Server it is like if I'm writing it in SQL... why if I'm sending the date 08/01/2013 as a string it doesn't return anything?



Thank you in advance. I'm not good in database, most things I look for them on the internet ^^







delphi sql-server-2005 datetime delphi-2010






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 9 '13 at 6:05









marc_s

567k12810981249




567k12810981249










asked Jan 9 '13 at 0:35









Edgar Holguin

96210




96210







  • 2




    BETWEEN is terrible for this, as is converting to a string to get rid of time. Try WHERE fecha_hora >= '20130801' AND fecha_hora < '20130802'... see sqlblog.com/blogs/aaron_bertrand/archive/2011/10/19/…, sqlperformance.com/2012/09/t-sql-queries/… and sqlperformance.com/2012/10/t-sql-queries/trim-time
    – Aaron Bertrand
    Jan 9 '13 at 1:27







  • 3




    What happens if someone enters Jose's Burrito for DBLUCB_tipo? (or creates a tipo with an apostrophe). This will lead to SQL syntax error. Parameterized queries will also avoid this problem! See also bobby-tables.com/delphi.html
    – Gerry Coll
    Jan 9 '13 at 5:19











  • @AaronBertrand I changed the way i deal with dates to yours, and it worked great, it might have not solved my question of why the code runs in SQL and not in delphi but it solved my problem and showed me a better way to use dates. Could you change it to an answere so i can set it as the answere?
    – Edgar Holguin
    Jan 10 '13 at 17:43












  • 2




    BETWEEN is terrible for this, as is converting to a string to get rid of time. Try WHERE fecha_hora >= '20130801' AND fecha_hora < '20130802'... see sqlblog.com/blogs/aaron_bertrand/archive/2011/10/19/…, sqlperformance.com/2012/09/t-sql-queries/… and sqlperformance.com/2012/10/t-sql-queries/trim-time
    – Aaron Bertrand
    Jan 9 '13 at 1:27







  • 3




    What happens if someone enters Jose's Burrito for DBLUCB_tipo? (or creates a tipo with an apostrophe). This will lead to SQL syntax error. Parameterized queries will also avoid this problem! See also bobby-tables.com/delphi.html
    – Gerry Coll
    Jan 9 '13 at 5:19











  • @AaronBertrand I changed the way i deal with dates to yours, and it worked great, it might have not solved my question of why the code runs in SQL and not in delphi but it solved my problem and showed me a better way to use dates. Could you change it to an answere so i can set it as the answere?
    – Edgar Holguin
    Jan 10 '13 at 17:43







2




2




BETWEEN is terrible for this, as is converting to a string to get rid of time. Try WHERE fecha_hora >= '20130801' AND fecha_hora < '20130802'... see sqlblog.com/blogs/aaron_bertrand/archive/2011/10/19/…, sqlperformance.com/2012/09/t-sql-queries/… and sqlperformance.com/2012/10/t-sql-queries/trim-time
– Aaron Bertrand
Jan 9 '13 at 1:27





BETWEEN is terrible for this, as is converting to a string to get rid of time. Try WHERE fecha_hora >= '20130801' AND fecha_hora < '20130802'... see sqlblog.com/blogs/aaron_bertrand/archive/2011/10/19/…, sqlperformance.com/2012/09/t-sql-queries/… and sqlperformance.com/2012/10/t-sql-queries/trim-time
– Aaron Bertrand
Jan 9 '13 at 1:27





3




3




What happens if someone enters Jose's Burrito for DBLUCB_tipo? (or creates a tipo with an apostrophe). This will lead to SQL syntax error. Parameterized queries will also avoid this problem! See also bobby-tables.com/delphi.html
– Gerry Coll
Jan 9 '13 at 5:19





What happens if someone enters Jose's Burrito for DBLUCB_tipo? (or creates a tipo with an apostrophe). This will lead to SQL syntax error. Parameterized queries will also avoid this problem! See also bobby-tables.com/delphi.html
– Gerry Coll
Jan 9 '13 at 5:19













@AaronBertrand I changed the way i deal with dates to yours, and it worked great, it might have not solved my question of why the code runs in SQL and not in delphi but it solved my problem and showed me a better way to use dates. Could you change it to an answere so i can set it as the answere?
– Edgar Holguin
Jan 10 '13 at 17:43




@AaronBertrand I changed the way i deal with dates to yours, and it worked great, it might have not solved my question of why the code runs in SQL and not in delphi but it solved my problem and showed me a better way to use dates. Could you change it to an answere so i can set it as the answere?
– Edgar Holguin
Jan 10 '13 at 17:43












4 Answers
4






active

oldest

votes

















up vote
1
down vote



accepted










You should avoid BETWEEN for date range queries, as well as avoid any ambiguous date formats such as m/d/y or d/m/y. The query you end up with should look like this (how you get there in your delphi code I'll leave up to you):



WHERE fecha_hora >= '20130801' AND fecha_hora < '20130802'


But better yet, as the others have suggested, you should be passing the date value in via a parameter, e.g.



WHERE fecha_hora >= @date_param AND fecha_hora < DATEADD(DAY, 1, @date_param)


(If you need other cases other than single day, then use two parameters.)



For more background on date/range queries and why this is the way you should do it:



  • What do BETWEEN and the devil have in common?


  • Bad habits to kick : mis-handling date / range queries


And why you shouldn't use CONVERT to remove time from datetime:



  • What is the most efficient way to trim time from datetime?


  • Trimming time from datetime – a follow-up






share|improve this answer





























    up vote
    9
    down vote













    You can avoid all these issues and wrote a very much cleaner code using parameterized queries.



    Try this



     conect.Q_total_hora.Active:=false;
    conect.Q_total_hora.SQL.Clear;
    conect.Q_total_hora.SQL.Add('select datepart(hh, fecha_hora) as Hora, sum(Total) as Venta, a.tipo as Tipo');
    conect.Q_total_hora.SQL.Add('from ventas v join articulos a on v.id_articulo=a.id_articulo');
    conect.Q_total_hora.SQL.Add('where tipo=:tipo and fecha_hora between :fecha1 and :fecha2');
    conect.Q_total_hora.SQL.Add('group by datepart(hh,fecha_hora), a.tipo order by datepart(hh,fecha_hora) ');
    conect.Q_total_hora.Prepared:=True;
    conect.Q_total_hora.ParamByName('tipo').AsString := DBLUCB_tipo.Text;
    conect.Q_total_hora.ParamByName('fecha1').AsDateTime := DateTimePicker_fecha1.Date;
    conect.Q_total_hora.ParamByName('fecha2').AsDateTime := DateTimePicker_fecha2.Date;
    conect.Q_total_hora.Open;





    share|improve this answer




















    • Maybe that new query will work, but the question asks for an explanation of why the given query doesn't work, not for alternatives.
      – Rob Kennedy
      Jan 9 '13 at 4:23







    • 3




      @RobKennedy, Why worry trying to find an explanation to an issue caused by a bad practice, as is passing datetime values as strings?
      – RRUZ
      Jan 9 '13 at 4:30






    • 1




      Giving a workaround and a advice, which is use parameters instead of use a literal sql sentence, is a valid answer too.
      – RRUZ
      Jan 9 '13 at 4:40






    • 2




      Using unparameterised queries without good reason is bad practice in general, using with DATE/DATETIME is even more so, for this very reason.
      – Gerry Coll
      Jan 9 '13 at 5:14






    • 1




      +1 for parameters. Death to injectable queries!!!
      – whosrdaddy
      Jan 9 '13 at 6:11

















    up vote
    2
    down vote













    Try this:



    conect.Q_total_hora.SQL.Add('where tipo='+char(39)+DBLUCB_tipo.Text+char(39)+' and fecha_hora between '+char(39)+DateToStr(DateTimePicker_fecha1.Date)+char(39)+ ' and '+char(39)+DateToStr(DateTimePicker_fecha2.Date)+char(39));


    which should look like:



    where tipo='Burrito Grande' and fecha_hora between '08/01/2013' and '08/01/2013'


    SQL should convert the dates to datetime automagically and do the where you want.



    You could also try this:



    where tipo='Burrito Grande' and month(fecha_hora) = 8 and year(fecha_hora) = 2013 and day(fecha_hora) = 1





    share|improve this answer






















    • it does't work and i believe is because of the time in smalldatetime. it would work if i use where tipo='Burrito Grande' and fecha_hora between '2013-08-01 00:00:00' and '2013-08-01 23:59:00' but i want to use only dates
      – Edgar Holguin
      Jan 9 '13 at 1:19







    • 3




      I strongly recommend against regional formats. Even I can't tell if you meant August 1st or January 8th.
      – Aaron Bertrand
      Jan 9 '13 at 1:29










    • Could you please describe what's different about your first suggested line of code? It looks similar to the original, and I was always lousy at those spot-the-differences games.
      – Rob Kennedy
      Jan 9 '13 at 4:20










    • @RobKennedy - I replaced cast(Convert(varchar(10), fecha_hora, 112) as datetime) with fecha_hora
      – Hogan
      Jan 9 '13 at 4:22


















    up vote
    2
    down vote













    If you use the term BETWEEN '08/01/2013' and '08/01/2013' you will indeed only see records having a date value of exactly '08/01/2013'.



    If the column is of type date you will get what you want, but as your column type is datetime, the contents '08/01/2013 11:22' is not between '08/01/2013 00:00:00' and '08/01/2013 00:00:00' and hence ignored.



    When querying a datetime column, use a pattern like this



    ...
    where DateTimeCol between '<StartDate>' and '<EndDate> 23:59:59,997'


    This might look a bit weird, but will include all datestamps from the given date range.



    Update: This is a dirty solution which only works well with data type DATETIME but will not work with SMALLDATETIME or DATETIME2.



    From my point of view there are two clean solutions: Either use



    where (DateTimeCol>='<StartDate>') 
    and (DateTimeCol <'<The day following the EndDate>')


    or separate date and time to two columns. Of course, only if possible and no ranges smaller than a day are required (eg one hour or so).






    share|improve this answer






















    • Note that this holds for parameterized queries as well.
      – Jeroen Wiert Pluimers
      Jan 9 '13 at 7:33










    • Thanks for pointing that out. In fact, I tried to answer the original question only. The advantages of parametrized queries are explained in full already.
      – alzaimar
      Jan 9 '13 at 7:36






    • 2




      @alzaimar you can also use StartOfTheDay/EndOfTheDay functions from DateUtils when passing Date/DateTime values.
      – LightBulb
      Jan 9 '13 at 14:30










    • @LightBulb: Thanks for the tip.
      – alzaimar
      Jan 9 '13 at 20:38










    • @LightBulb What would EndOfTheDay yield exactly? Does it understand the different data types, and how this can round up or miss data depending on whether the underlying data type is SMALLDATETIME, DATETIME, DATETIME2, etc.? Please see sqlblog.com/blogs/aaron_bertrand/archive/2011/10/19/… for why you never want to calculate the "end" of a range so that you can use BETWEEN - always calculate the start of the next range and use less than.
      – Aaron Bertrand
      Jan 10 '13 at 18:21










    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f14226516%2fsql-server-2005-query-works-in-sql-server-management-studio-express-but-not-in-d%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    4 Answers
    4






    active

    oldest

    votes








    4 Answers
    4






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    1
    down vote



    accepted










    You should avoid BETWEEN for date range queries, as well as avoid any ambiguous date formats such as m/d/y or d/m/y. The query you end up with should look like this (how you get there in your delphi code I'll leave up to you):



    WHERE fecha_hora >= '20130801' AND fecha_hora < '20130802'


    But better yet, as the others have suggested, you should be passing the date value in via a parameter, e.g.



    WHERE fecha_hora >= @date_param AND fecha_hora < DATEADD(DAY, 1, @date_param)


    (If you need other cases other than single day, then use two parameters.)



    For more background on date/range queries and why this is the way you should do it:



    • What do BETWEEN and the devil have in common?


    • Bad habits to kick : mis-handling date / range queries


    And why you shouldn't use CONVERT to remove time from datetime:



    • What is the most efficient way to trim time from datetime?


    • Trimming time from datetime – a follow-up






    share|improve this answer


























      up vote
      1
      down vote



      accepted










      You should avoid BETWEEN for date range queries, as well as avoid any ambiguous date formats such as m/d/y or d/m/y. The query you end up with should look like this (how you get there in your delphi code I'll leave up to you):



      WHERE fecha_hora >= '20130801' AND fecha_hora < '20130802'


      But better yet, as the others have suggested, you should be passing the date value in via a parameter, e.g.



      WHERE fecha_hora >= @date_param AND fecha_hora < DATEADD(DAY, 1, @date_param)


      (If you need other cases other than single day, then use two parameters.)



      For more background on date/range queries and why this is the way you should do it:



      • What do BETWEEN and the devil have in common?


      • Bad habits to kick : mis-handling date / range queries


      And why you shouldn't use CONVERT to remove time from datetime:



      • What is the most efficient way to trim time from datetime?


      • Trimming time from datetime – a follow-up






      share|improve this answer
























        up vote
        1
        down vote



        accepted







        up vote
        1
        down vote



        accepted






        You should avoid BETWEEN for date range queries, as well as avoid any ambiguous date formats such as m/d/y or d/m/y. The query you end up with should look like this (how you get there in your delphi code I'll leave up to you):



        WHERE fecha_hora >= '20130801' AND fecha_hora < '20130802'


        But better yet, as the others have suggested, you should be passing the date value in via a parameter, e.g.



        WHERE fecha_hora >= @date_param AND fecha_hora < DATEADD(DAY, 1, @date_param)


        (If you need other cases other than single day, then use two parameters.)



        For more background on date/range queries and why this is the way you should do it:



        • What do BETWEEN and the devil have in common?


        • Bad habits to kick : mis-handling date / range queries


        And why you shouldn't use CONVERT to remove time from datetime:



        • What is the most efficient way to trim time from datetime?


        • Trimming time from datetime – a follow-up






        share|improve this answer














        You should avoid BETWEEN for date range queries, as well as avoid any ambiguous date formats such as m/d/y or d/m/y. The query you end up with should look like this (how you get there in your delphi code I'll leave up to you):



        WHERE fecha_hora >= '20130801' AND fecha_hora < '20130802'


        But better yet, as the others have suggested, you should be passing the date value in via a parameter, e.g.



        WHERE fecha_hora >= @date_param AND fecha_hora < DATEADD(DAY, 1, @date_param)


        (If you need other cases other than single day, then use two parameters.)



        For more background on date/range queries and why this is the way you should do it:



        • What do BETWEEN and the devil have in common?


        • Bad habits to kick : mis-handling date / range queries


        And why you shouldn't use CONVERT to remove time from datetime:



        • What is the most efficient way to trim time from datetime?


        • Trimming time from datetime – a follow-up







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 11 at 13:54

























        answered Jan 10 '13 at 18:17









        Aaron Bertrand

        206k27361402




        206k27361402






















            up vote
            9
            down vote













            You can avoid all these issues and wrote a very much cleaner code using parameterized queries.



            Try this



             conect.Q_total_hora.Active:=false;
            conect.Q_total_hora.SQL.Clear;
            conect.Q_total_hora.SQL.Add('select datepart(hh, fecha_hora) as Hora, sum(Total) as Venta, a.tipo as Tipo');
            conect.Q_total_hora.SQL.Add('from ventas v join articulos a on v.id_articulo=a.id_articulo');
            conect.Q_total_hora.SQL.Add('where tipo=:tipo and fecha_hora between :fecha1 and :fecha2');
            conect.Q_total_hora.SQL.Add('group by datepart(hh,fecha_hora), a.tipo order by datepart(hh,fecha_hora) ');
            conect.Q_total_hora.Prepared:=True;
            conect.Q_total_hora.ParamByName('tipo').AsString := DBLUCB_tipo.Text;
            conect.Q_total_hora.ParamByName('fecha1').AsDateTime := DateTimePicker_fecha1.Date;
            conect.Q_total_hora.ParamByName('fecha2').AsDateTime := DateTimePicker_fecha2.Date;
            conect.Q_total_hora.Open;





            share|improve this answer




















            • Maybe that new query will work, but the question asks for an explanation of why the given query doesn't work, not for alternatives.
              – Rob Kennedy
              Jan 9 '13 at 4:23







            • 3




              @RobKennedy, Why worry trying to find an explanation to an issue caused by a bad practice, as is passing datetime values as strings?
              – RRUZ
              Jan 9 '13 at 4:30






            • 1




              Giving a workaround and a advice, which is use parameters instead of use a literal sql sentence, is a valid answer too.
              – RRUZ
              Jan 9 '13 at 4:40






            • 2




              Using unparameterised queries without good reason is bad practice in general, using with DATE/DATETIME is even more so, for this very reason.
              – Gerry Coll
              Jan 9 '13 at 5:14






            • 1




              +1 for parameters. Death to injectable queries!!!
              – whosrdaddy
              Jan 9 '13 at 6:11














            up vote
            9
            down vote













            You can avoid all these issues and wrote a very much cleaner code using parameterized queries.



            Try this



             conect.Q_total_hora.Active:=false;
            conect.Q_total_hora.SQL.Clear;
            conect.Q_total_hora.SQL.Add('select datepart(hh, fecha_hora) as Hora, sum(Total) as Venta, a.tipo as Tipo');
            conect.Q_total_hora.SQL.Add('from ventas v join articulos a on v.id_articulo=a.id_articulo');
            conect.Q_total_hora.SQL.Add('where tipo=:tipo and fecha_hora between :fecha1 and :fecha2');
            conect.Q_total_hora.SQL.Add('group by datepart(hh,fecha_hora), a.tipo order by datepart(hh,fecha_hora) ');
            conect.Q_total_hora.Prepared:=True;
            conect.Q_total_hora.ParamByName('tipo').AsString := DBLUCB_tipo.Text;
            conect.Q_total_hora.ParamByName('fecha1').AsDateTime := DateTimePicker_fecha1.Date;
            conect.Q_total_hora.ParamByName('fecha2').AsDateTime := DateTimePicker_fecha2.Date;
            conect.Q_total_hora.Open;





            share|improve this answer




















            • Maybe that new query will work, but the question asks for an explanation of why the given query doesn't work, not for alternatives.
              – Rob Kennedy
              Jan 9 '13 at 4:23







            • 3




              @RobKennedy, Why worry trying to find an explanation to an issue caused by a bad practice, as is passing datetime values as strings?
              – RRUZ
              Jan 9 '13 at 4:30






            • 1




              Giving a workaround and a advice, which is use parameters instead of use a literal sql sentence, is a valid answer too.
              – RRUZ
              Jan 9 '13 at 4:40






            • 2




              Using unparameterised queries without good reason is bad practice in general, using with DATE/DATETIME is even more so, for this very reason.
              – Gerry Coll
              Jan 9 '13 at 5:14






            • 1




              +1 for parameters. Death to injectable queries!!!
              – whosrdaddy
              Jan 9 '13 at 6:11












            up vote
            9
            down vote










            up vote
            9
            down vote









            You can avoid all these issues and wrote a very much cleaner code using parameterized queries.



            Try this



             conect.Q_total_hora.Active:=false;
            conect.Q_total_hora.SQL.Clear;
            conect.Q_total_hora.SQL.Add('select datepart(hh, fecha_hora) as Hora, sum(Total) as Venta, a.tipo as Tipo');
            conect.Q_total_hora.SQL.Add('from ventas v join articulos a on v.id_articulo=a.id_articulo');
            conect.Q_total_hora.SQL.Add('where tipo=:tipo and fecha_hora between :fecha1 and :fecha2');
            conect.Q_total_hora.SQL.Add('group by datepart(hh,fecha_hora), a.tipo order by datepart(hh,fecha_hora) ');
            conect.Q_total_hora.Prepared:=True;
            conect.Q_total_hora.ParamByName('tipo').AsString := DBLUCB_tipo.Text;
            conect.Q_total_hora.ParamByName('fecha1').AsDateTime := DateTimePicker_fecha1.Date;
            conect.Q_total_hora.ParamByName('fecha2').AsDateTime := DateTimePicker_fecha2.Date;
            conect.Q_total_hora.Open;





            share|improve this answer












            You can avoid all these issues and wrote a very much cleaner code using parameterized queries.



            Try this



             conect.Q_total_hora.Active:=false;
            conect.Q_total_hora.SQL.Clear;
            conect.Q_total_hora.SQL.Add('select datepart(hh, fecha_hora) as Hora, sum(Total) as Venta, a.tipo as Tipo');
            conect.Q_total_hora.SQL.Add('from ventas v join articulos a on v.id_articulo=a.id_articulo');
            conect.Q_total_hora.SQL.Add('where tipo=:tipo and fecha_hora between :fecha1 and :fecha2');
            conect.Q_total_hora.SQL.Add('group by datepart(hh,fecha_hora), a.tipo order by datepart(hh,fecha_hora) ');
            conect.Q_total_hora.Prepared:=True;
            conect.Q_total_hora.ParamByName('tipo').AsString := DBLUCB_tipo.Text;
            conect.Q_total_hora.ParamByName('fecha1').AsDateTime := DateTimePicker_fecha1.Date;
            conect.Q_total_hora.ParamByName('fecha2').AsDateTime := DateTimePicker_fecha2.Date;
            conect.Q_total_hora.Open;






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Jan 9 '13 at 1:52









            RRUZ

            123k13303438




            123k13303438











            • Maybe that new query will work, but the question asks for an explanation of why the given query doesn't work, not for alternatives.
              – Rob Kennedy
              Jan 9 '13 at 4:23







            • 3




              @RobKennedy, Why worry trying to find an explanation to an issue caused by a bad practice, as is passing datetime values as strings?
              – RRUZ
              Jan 9 '13 at 4:30






            • 1




              Giving a workaround and a advice, which is use parameters instead of use a literal sql sentence, is a valid answer too.
              – RRUZ
              Jan 9 '13 at 4:40






            • 2




              Using unparameterised queries without good reason is bad practice in general, using with DATE/DATETIME is even more so, for this very reason.
              – Gerry Coll
              Jan 9 '13 at 5:14






            • 1




              +1 for parameters. Death to injectable queries!!!
              – whosrdaddy
              Jan 9 '13 at 6:11
















            • Maybe that new query will work, but the question asks for an explanation of why the given query doesn't work, not for alternatives.
              – Rob Kennedy
              Jan 9 '13 at 4:23







            • 3




              @RobKennedy, Why worry trying to find an explanation to an issue caused by a bad practice, as is passing datetime values as strings?
              – RRUZ
              Jan 9 '13 at 4:30






            • 1




              Giving a workaround and a advice, which is use parameters instead of use a literal sql sentence, is a valid answer too.
              – RRUZ
              Jan 9 '13 at 4:40






            • 2




              Using unparameterised queries without good reason is bad practice in general, using with DATE/DATETIME is even more so, for this very reason.
              – Gerry Coll
              Jan 9 '13 at 5:14






            • 1




              +1 for parameters. Death to injectable queries!!!
              – whosrdaddy
              Jan 9 '13 at 6:11















            Maybe that new query will work, but the question asks for an explanation of why the given query doesn't work, not for alternatives.
            – Rob Kennedy
            Jan 9 '13 at 4:23





            Maybe that new query will work, but the question asks for an explanation of why the given query doesn't work, not for alternatives.
            – Rob Kennedy
            Jan 9 '13 at 4:23





            3




            3




            @RobKennedy, Why worry trying to find an explanation to an issue caused by a bad practice, as is passing datetime values as strings?
            – RRUZ
            Jan 9 '13 at 4:30




            @RobKennedy, Why worry trying to find an explanation to an issue caused by a bad practice, as is passing datetime values as strings?
            – RRUZ
            Jan 9 '13 at 4:30




            1




            1




            Giving a workaround and a advice, which is use parameters instead of use a literal sql sentence, is a valid answer too.
            – RRUZ
            Jan 9 '13 at 4:40




            Giving a workaround and a advice, which is use parameters instead of use a literal sql sentence, is a valid answer too.
            – RRUZ
            Jan 9 '13 at 4:40




            2




            2




            Using unparameterised queries without good reason is bad practice in general, using with DATE/DATETIME is even more so, for this very reason.
            – Gerry Coll
            Jan 9 '13 at 5:14




            Using unparameterised queries without good reason is bad practice in general, using with DATE/DATETIME is even more so, for this very reason.
            – Gerry Coll
            Jan 9 '13 at 5:14




            1




            1




            +1 for parameters. Death to injectable queries!!!
            – whosrdaddy
            Jan 9 '13 at 6:11




            +1 for parameters. Death to injectable queries!!!
            – whosrdaddy
            Jan 9 '13 at 6:11










            up vote
            2
            down vote













            Try this:



            conect.Q_total_hora.SQL.Add('where tipo='+char(39)+DBLUCB_tipo.Text+char(39)+' and fecha_hora between '+char(39)+DateToStr(DateTimePicker_fecha1.Date)+char(39)+ ' and '+char(39)+DateToStr(DateTimePicker_fecha2.Date)+char(39));


            which should look like:



            where tipo='Burrito Grande' and fecha_hora between '08/01/2013' and '08/01/2013'


            SQL should convert the dates to datetime automagically and do the where you want.



            You could also try this:



            where tipo='Burrito Grande' and month(fecha_hora) = 8 and year(fecha_hora) = 2013 and day(fecha_hora) = 1





            share|improve this answer






















            • it does't work and i believe is because of the time in smalldatetime. it would work if i use where tipo='Burrito Grande' and fecha_hora between '2013-08-01 00:00:00' and '2013-08-01 23:59:00' but i want to use only dates
              – Edgar Holguin
              Jan 9 '13 at 1:19







            • 3




              I strongly recommend against regional formats. Even I can't tell if you meant August 1st or January 8th.
              – Aaron Bertrand
              Jan 9 '13 at 1:29










            • Could you please describe what's different about your first suggested line of code? It looks similar to the original, and I was always lousy at those spot-the-differences games.
              – Rob Kennedy
              Jan 9 '13 at 4:20










            • @RobKennedy - I replaced cast(Convert(varchar(10), fecha_hora, 112) as datetime) with fecha_hora
              – Hogan
              Jan 9 '13 at 4:22















            up vote
            2
            down vote













            Try this:



            conect.Q_total_hora.SQL.Add('where tipo='+char(39)+DBLUCB_tipo.Text+char(39)+' and fecha_hora between '+char(39)+DateToStr(DateTimePicker_fecha1.Date)+char(39)+ ' and '+char(39)+DateToStr(DateTimePicker_fecha2.Date)+char(39));


            which should look like:



            where tipo='Burrito Grande' and fecha_hora between '08/01/2013' and '08/01/2013'


            SQL should convert the dates to datetime automagically and do the where you want.



            You could also try this:



            where tipo='Burrito Grande' and month(fecha_hora) = 8 and year(fecha_hora) = 2013 and day(fecha_hora) = 1





            share|improve this answer






















            • it does't work and i believe is because of the time in smalldatetime. it would work if i use where tipo='Burrito Grande' and fecha_hora between '2013-08-01 00:00:00' and '2013-08-01 23:59:00' but i want to use only dates
              – Edgar Holguin
              Jan 9 '13 at 1:19







            • 3




              I strongly recommend against regional formats. Even I can't tell if you meant August 1st or January 8th.
              – Aaron Bertrand
              Jan 9 '13 at 1:29










            • Could you please describe what's different about your first suggested line of code? It looks similar to the original, and I was always lousy at those spot-the-differences games.
              – Rob Kennedy
              Jan 9 '13 at 4:20










            • @RobKennedy - I replaced cast(Convert(varchar(10), fecha_hora, 112) as datetime) with fecha_hora
              – Hogan
              Jan 9 '13 at 4:22













            up vote
            2
            down vote










            up vote
            2
            down vote









            Try this:



            conect.Q_total_hora.SQL.Add('where tipo='+char(39)+DBLUCB_tipo.Text+char(39)+' and fecha_hora between '+char(39)+DateToStr(DateTimePicker_fecha1.Date)+char(39)+ ' and '+char(39)+DateToStr(DateTimePicker_fecha2.Date)+char(39));


            which should look like:



            where tipo='Burrito Grande' and fecha_hora between '08/01/2013' and '08/01/2013'


            SQL should convert the dates to datetime automagically and do the where you want.



            You could also try this:



            where tipo='Burrito Grande' and month(fecha_hora) = 8 and year(fecha_hora) = 2013 and day(fecha_hora) = 1





            share|improve this answer














            Try this:



            conect.Q_total_hora.SQL.Add('where tipo='+char(39)+DBLUCB_tipo.Text+char(39)+' and fecha_hora between '+char(39)+DateToStr(DateTimePicker_fecha1.Date)+char(39)+ ' and '+char(39)+DateToStr(DateTimePicker_fecha2.Date)+char(39));


            which should look like:



            where tipo='Burrito Grande' and fecha_hora between '08/01/2013' and '08/01/2013'


            SQL should convert the dates to datetime automagically and do the where you want.



            You could also try this:



            where tipo='Burrito Grande' and month(fecha_hora) = 8 and year(fecha_hora) = 2013 and day(fecha_hora) = 1






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Jan 9 '13 at 2:21

























            answered Jan 9 '13 at 0:55









            Hogan

            54.2k863102




            54.2k863102











            • it does't work and i believe is because of the time in smalldatetime. it would work if i use where tipo='Burrito Grande' and fecha_hora between '2013-08-01 00:00:00' and '2013-08-01 23:59:00' but i want to use only dates
              – Edgar Holguin
              Jan 9 '13 at 1:19







            • 3




              I strongly recommend against regional formats. Even I can't tell if you meant August 1st or January 8th.
              – Aaron Bertrand
              Jan 9 '13 at 1:29










            • Could you please describe what's different about your first suggested line of code? It looks similar to the original, and I was always lousy at those spot-the-differences games.
              – Rob Kennedy
              Jan 9 '13 at 4:20










            • @RobKennedy - I replaced cast(Convert(varchar(10), fecha_hora, 112) as datetime) with fecha_hora
              – Hogan
              Jan 9 '13 at 4:22

















            • it does't work and i believe is because of the time in smalldatetime. it would work if i use where tipo='Burrito Grande' and fecha_hora between '2013-08-01 00:00:00' and '2013-08-01 23:59:00' but i want to use only dates
              – Edgar Holguin
              Jan 9 '13 at 1:19







            • 3




              I strongly recommend against regional formats. Even I can't tell if you meant August 1st or January 8th.
              – Aaron Bertrand
              Jan 9 '13 at 1:29










            • Could you please describe what's different about your first suggested line of code? It looks similar to the original, and I was always lousy at those spot-the-differences games.
              – Rob Kennedy
              Jan 9 '13 at 4:20










            • @RobKennedy - I replaced cast(Convert(varchar(10), fecha_hora, 112) as datetime) with fecha_hora
              – Hogan
              Jan 9 '13 at 4:22
















            it does't work and i believe is because of the time in smalldatetime. it would work if i use where tipo='Burrito Grande' and fecha_hora between '2013-08-01 00:00:00' and '2013-08-01 23:59:00' but i want to use only dates
            – Edgar Holguin
            Jan 9 '13 at 1:19





            it does't work and i believe is because of the time in smalldatetime. it would work if i use where tipo='Burrito Grande' and fecha_hora between '2013-08-01 00:00:00' and '2013-08-01 23:59:00' but i want to use only dates
            – Edgar Holguin
            Jan 9 '13 at 1:19





            3




            3




            I strongly recommend against regional formats. Even I can't tell if you meant August 1st or January 8th.
            – Aaron Bertrand
            Jan 9 '13 at 1:29




            I strongly recommend against regional formats. Even I can't tell if you meant August 1st or January 8th.
            – Aaron Bertrand
            Jan 9 '13 at 1:29












            Could you please describe what's different about your first suggested line of code? It looks similar to the original, and I was always lousy at those spot-the-differences games.
            – Rob Kennedy
            Jan 9 '13 at 4:20




            Could you please describe what's different about your first suggested line of code? It looks similar to the original, and I was always lousy at those spot-the-differences games.
            – Rob Kennedy
            Jan 9 '13 at 4:20












            @RobKennedy - I replaced cast(Convert(varchar(10), fecha_hora, 112) as datetime) with fecha_hora
            – Hogan
            Jan 9 '13 at 4:22





            @RobKennedy - I replaced cast(Convert(varchar(10), fecha_hora, 112) as datetime) with fecha_hora
            – Hogan
            Jan 9 '13 at 4:22











            up vote
            2
            down vote













            If you use the term BETWEEN '08/01/2013' and '08/01/2013' you will indeed only see records having a date value of exactly '08/01/2013'.



            If the column is of type date you will get what you want, but as your column type is datetime, the contents '08/01/2013 11:22' is not between '08/01/2013 00:00:00' and '08/01/2013 00:00:00' and hence ignored.



            When querying a datetime column, use a pattern like this



            ...
            where DateTimeCol between '<StartDate>' and '<EndDate> 23:59:59,997'


            This might look a bit weird, but will include all datestamps from the given date range.



            Update: This is a dirty solution which only works well with data type DATETIME but will not work with SMALLDATETIME or DATETIME2.



            From my point of view there are two clean solutions: Either use



            where (DateTimeCol>='<StartDate>') 
            and (DateTimeCol <'<The day following the EndDate>')


            or separate date and time to two columns. Of course, only if possible and no ranges smaller than a day are required (eg one hour or so).






            share|improve this answer






















            • Note that this holds for parameterized queries as well.
              – Jeroen Wiert Pluimers
              Jan 9 '13 at 7:33










            • Thanks for pointing that out. In fact, I tried to answer the original question only. The advantages of parametrized queries are explained in full already.
              – alzaimar
              Jan 9 '13 at 7:36






            • 2




              @alzaimar you can also use StartOfTheDay/EndOfTheDay functions from DateUtils when passing Date/DateTime values.
              – LightBulb
              Jan 9 '13 at 14:30










            • @LightBulb: Thanks for the tip.
              – alzaimar
              Jan 9 '13 at 20:38










            • @LightBulb What would EndOfTheDay yield exactly? Does it understand the different data types, and how this can round up or miss data depending on whether the underlying data type is SMALLDATETIME, DATETIME, DATETIME2, etc.? Please see sqlblog.com/blogs/aaron_bertrand/archive/2011/10/19/… for why you never want to calculate the "end" of a range so that you can use BETWEEN - always calculate the start of the next range and use less than.
              – Aaron Bertrand
              Jan 10 '13 at 18:21














            up vote
            2
            down vote













            If you use the term BETWEEN '08/01/2013' and '08/01/2013' you will indeed only see records having a date value of exactly '08/01/2013'.



            If the column is of type date you will get what you want, but as your column type is datetime, the contents '08/01/2013 11:22' is not between '08/01/2013 00:00:00' and '08/01/2013 00:00:00' and hence ignored.



            When querying a datetime column, use a pattern like this



            ...
            where DateTimeCol between '<StartDate>' and '<EndDate> 23:59:59,997'


            This might look a bit weird, but will include all datestamps from the given date range.



            Update: This is a dirty solution which only works well with data type DATETIME but will not work with SMALLDATETIME or DATETIME2.



            From my point of view there are two clean solutions: Either use



            where (DateTimeCol>='<StartDate>') 
            and (DateTimeCol <'<The day following the EndDate>')


            or separate date and time to two columns. Of course, only if possible and no ranges smaller than a day are required (eg one hour or so).






            share|improve this answer






















            • Note that this holds for parameterized queries as well.
              – Jeroen Wiert Pluimers
              Jan 9 '13 at 7:33










            • Thanks for pointing that out. In fact, I tried to answer the original question only. The advantages of parametrized queries are explained in full already.
              – alzaimar
              Jan 9 '13 at 7:36






            • 2




              @alzaimar you can also use StartOfTheDay/EndOfTheDay functions from DateUtils when passing Date/DateTime values.
              – LightBulb
              Jan 9 '13 at 14:30










            • @LightBulb: Thanks for the tip.
              – alzaimar
              Jan 9 '13 at 20:38










            • @LightBulb What would EndOfTheDay yield exactly? Does it understand the different data types, and how this can round up or miss data depending on whether the underlying data type is SMALLDATETIME, DATETIME, DATETIME2, etc.? Please see sqlblog.com/blogs/aaron_bertrand/archive/2011/10/19/… for why you never want to calculate the "end" of a range so that you can use BETWEEN - always calculate the start of the next range and use less than.
              – Aaron Bertrand
              Jan 10 '13 at 18:21












            up vote
            2
            down vote










            up vote
            2
            down vote









            If you use the term BETWEEN '08/01/2013' and '08/01/2013' you will indeed only see records having a date value of exactly '08/01/2013'.



            If the column is of type date you will get what you want, but as your column type is datetime, the contents '08/01/2013 11:22' is not between '08/01/2013 00:00:00' and '08/01/2013 00:00:00' and hence ignored.



            When querying a datetime column, use a pattern like this



            ...
            where DateTimeCol between '<StartDate>' and '<EndDate> 23:59:59,997'


            This might look a bit weird, but will include all datestamps from the given date range.



            Update: This is a dirty solution which only works well with data type DATETIME but will not work with SMALLDATETIME or DATETIME2.



            From my point of view there are two clean solutions: Either use



            where (DateTimeCol>='<StartDate>') 
            and (DateTimeCol <'<The day following the EndDate>')


            or separate date and time to two columns. Of course, only if possible and no ranges smaller than a day are required (eg one hour or so).






            share|improve this answer














            If you use the term BETWEEN '08/01/2013' and '08/01/2013' you will indeed only see records having a date value of exactly '08/01/2013'.



            If the column is of type date you will get what you want, but as your column type is datetime, the contents '08/01/2013 11:22' is not between '08/01/2013 00:00:00' and '08/01/2013 00:00:00' and hence ignored.



            When querying a datetime column, use a pattern like this



            ...
            where DateTimeCol between '<StartDate>' and '<EndDate> 23:59:59,997'


            This might look a bit weird, but will include all datestamps from the given date range.



            Update: This is a dirty solution which only works well with data type DATETIME but will not work with SMALLDATETIME or DATETIME2.



            From my point of view there are two clean solutions: Either use



            where (DateTimeCol>='<StartDate>') 
            and (DateTimeCol <'<The day following the EndDate>')


            or separate date and time to two columns. Of course, only if possible and no ranges smaller than a day are required (eg one hour or so).







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Jan 11 '13 at 6:55

























            answered Jan 9 '13 at 7:21









            alzaimar

            4,00311124




            4,00311124











            • Note that this holds for parameterized queries as well.
              – Jeroen Wiert Pluimers
              Jan 9 '13 at 7:33










            • Thanks for pointing that out. In fact, I tried to answer the original question only. The advantages of parametrized queries are explained in full already.
              – alzaimar
              Jan 9 '13 at 7:36






            • 2




              @alzaimar you can also use StartOfTheDay/EndOfTheDay functions from DateUtils when passing Date/DateTime values.
              – LightBulb
              Jan 9 '13 at 14:30










            • @LightBulb: Thanks for the tip.
              – alzaimar
              Jan 9 '13 at 20:38










            • @LightBulb What would EndOfTheDay yield exactly? Does it understand the different data types, and how this can round up or miss data depending on whether the underlying data type is SMALLDATETIME, DATETIME, DATETIME2, etc.? Please see sqlblog.com/blogs/aaron_bertrand/archive/2011/10/19/… for why you never want to calculate the "end" of a range so that you can use BETWEEN - always calculate the start of the next range and use less than.
              – Aaron Bertrand
              Jan 10 '13 at 18:21
















            • Note that this holds for parameterized queries as well.
              – Jeroen Wiert Pluimers
              Jan 9 '13 at 7:33










            • Thanks for pointing that out. In fact, I tried to answer the original question only. The advantages of parametrized queries are explained in full already.
              – alzaimar
              Jan 9 '13 at 7:36






            • 2




              @alzaimar you can also use StartOfTheDay/EndOfTheDay functions from DateUtils when passing Date/DateTime values.
              – LightBulb
              Jan 9 '13 at 14:30










            • @LightBulb: Thanks for the tip.
              – alzaimar
              Jan 9 '13 at 20:38










            • @LightBulb What would EndOfTheDay yield exactly? Does it understand the different data types, and how this can round up or miss data depending on whether the underlying data type is SMALLDATETIME, DATETIME, DATETIME2, etc.? Please see sqlblog.com/blogs/aaron_bertrand/archive/2011/10/19/… for why you never want to calculate the "end" of a range so that you can use BETWEEN - always calculate the start of the next range and use less than.
              – Aaron Bertrand
              Jan 10 '13 at 18:21















            Note that this holds for parameterized queries as well.
            – Jeroen Wiert Pluimers
            Jan 9 '13 at 7:33




            Note that this holds for parameterized queries as well.
            – Jeroen Wiert Pluimers
            Jan 9 '13 at 7:33












            Thanks for pointing that out. In fact, I tried to answer the original question only. The advantages of parametrized queries are explained in full already.
            – alzaimar
            Jan 9 '13 at 7:36




            Thanks for pointing that out. In fact, I tried to answer the original question only. The advantages of parametrized queries are explained in full already.
            – alzaimar
            Jan 9 '13 at 7:36




            2




            2




            @alzaimar you can also use StartOfTheDay/EndOfTheDay functions from DateUtils when passing Date/DateTime values.
            – LightBulb
            Jan 9 '13 at 14:30




            @alzaimar you can also use StartOfTheDay/EndOfTheDay functions from DateUtils when passing Date/DateTime values.
            – LightBulb
            Jan 9 '13 at 14:30












            @LightBulb: Thanks for the tip.
            – alzaimar
            Jan 9 '13 at 20:38




            @LightBulb: Thanks for the tip.
            – alzaimar
            Jan 9 '13 at 20:38












            @LightBulb What would EndOfTheDay yield exactly? Does it understand the different data types, and how this can round up or miss data depending on whether the underlying data type is SMALLDATETIME, DATETIME, DATETIME2, etc.? Please see sqlblog.com/blogs/aaron_bertrand/archive/2011/10/19/… for why you never want to calculate the "end" of a range so that you can use BETWEEN - always calculate the start of the next range and use less than.
            – Aaron Bertrand
            Jan 10 '13 at 18:21




            @LightBulb What would EndOfTheDay yield exactly? Does it understand the different data types, and how this can round up or miss data depending on whether the underlying data type is SMALLDATETIME, DATETIME, DATETIME2, etc.? Please see sqlblog.com/blogs/aaron_bertrand/archive/2011/10/19/… for why you never want to calculate the "end" of a range so that you can use BETWEEN - always calculate the start of the next range and use less than.
            – Aaron Bertrand
            Jan 10 '13 at 18:21

















            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f14226516%2fsql-server-2005-query-works-in-sql-server-management-studio-express-but-not-in-d%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            這個網誌中的熱門文章

            Barbados

            How to read a connectionString WITH PROVIDER in .NET Core?

            Node.js Script on GitHub Pages or Amazon S3