【发布时间】:2013-01-09 00:35:29
【问题描述】:
我正在使用 SQL Server 2005 Management Studio Express 和 Delphi 2010。Fecha_hora = Date_Time 是 smalldatetime。
我的日期格式是dd/mm/yyy
我表中的日期是这样保存的:
08/01/2013 11:22:00 a.m.
我在 Delphi 中有此查询,以了解给定一段时间内的销售额在哪个时间段更高;天/月,在这种情况下,我在 2013 年 1 月 8 日的同一天进行测试:
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;
我使用cast(Convert(varchar(10), fecha_hora, 112) as datetime)是因为我在互联网上发现这样我只能检索日期而没有时间检索日期之间的数据。
在DateTimePickers 中,我选择08/01/2013 作为 2013 年 1 月 8 日
我用备忘录查看查询memo1.Text:=conect.Q_total_hora.Text;
我收到的查询是:
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)
我遇到的问题是,当我在 SQL Server Mgmt Studio 中运行此查询时,它返回值,但不在 Delphi 中,如果我将 DateTimePickers 的值设置为 01/08/2013 为 2013 年 8 月 1 日,则在 Delphi 中它返回08/01/2012 的值。
据我所知(而且我知道的不多……)当我向 SQL Server 发送查询时,就像我用 SQL 编写它一样……为什么要发送日期08/01/2013 作为字符串不返回任何内容?
提前谢谢你。我不擅长数据库,大部分东西我都在网上找他们^^
【问题讨论】:
-
BETWEEN对此很糟糕,因为转换为字符串以摆脱时间也是如此。试试WHERE fecha_hora >= '20130801' AND fecha_hora < '20130802'...见sqlblog.com/blogs/aaron_bertrand/archive/2011/10/19/…、sqlperformance.com/2012/09/t-sql-queries/…和sqlperformance.com/2012/10/t-sql-queries/trim-time -
如果有人为 DBLUCB_tipo 输入
Jose's Burrito会发生什么? (或用撇号创建一个tipo)。这将导致 SQL 语法错误。参数化查询也可以避免这个问题!另见bobby-tables.com/delphi.html -
@AaronBertrand 我将处理日期的方式更改为您的,效果很好,它可能没有解决我的问题,即为什么代码在 SQL 而不是在 delphi 中运行,但它解决了我的问题和向我展示了使用日期的更好方法。你能把它改成一个回答者,这样我就可以把它设置为回答者吗?
标签: delphi sql-server-2005 datetime delphi-2010