Linq-to-SQL日期格式:查询不起作用

时间:2011-11-24 13:45:29

标签: c# sql-server linq-to-sql datetimepicker

我在SQL Server中执行此查询时有一个存储过程

exec SelectOfficeNameGroup  '2011-10-05', '2011-11-09', ''

它返回110行。

现在我在c#3.5表单上有两个datepicker和一个执行查询的按钮:

var result = context.SelectOfficeNameGroup(dateTimePickerFrom.Value, dateTimePickerTo.Value, "");

但它只返回2行。

我的日期选择器格式为MM/DD/YYYY

这是我的程序

ALTER PROC [dbo].[SelectOfficeNameGroup]
  @From datetime,
  @To datetime,
  @OfficeName nvarchar(50)
AS
BEGIN
   SELECT
      ID AS ProductID, OfficeName,  
      SUM(Quantity) AS Quantity, 
      SUM(TotalPrice) AS TotalPrice, 
      Category
   FROM
      ProductLogWithCategory 
   WHERE 
      DateTime BETWEEN @From AND @To AND OfficeName = @OfficeName
   GROUP BY 
      OfficeName, ID, Category

  return
END

有什么建议吗?

2 个答案:

答案 0 :(得分:1)

尝试

var result = context.SelectOfficeNameGroup(dateTimePickerFrom.Value.ToString("yyyy-MM-dd"), dateTimePickerTo.Value.ToString("yyyy-MM-dd"), "");

查看DateTime.ToString documentation


<强>更新

为了安全起见,试试

ALTER PROC [dbo].[SelectOfficeNameGroup]
  @From varchar(8),
  @To varchar(8),
  @OfficeName nvarchar(50)
AS
BEGIN
   SELECT
      ID AS ProductID, OfficeName,  
      SUM(Quantity) AS Quantity, 
      SUM(TotalPrice) AS TotalPrice, 
      Category
   FROM
      ProductLogWithCategory 
   WHERE 
      DateTime BETWEEN @From AND @To AND OfficeName = @OfficeName
   GROUP BY 
      OfficeName, ID, Category

  return
END

并像这样使用

来自sql

exec SelectOfficeNameGroup  '20111005', '20111109', ''
来自linq的

var result = context.SelectOfficeNameGroup(dateTimePickerFrom.Value.ToString("yyyyMMdd"), dateTimePickerTo.Value.ToString("yyyyMMdd"), "");

答案 1 :(得分:0)

DateTime.Parse('your date in MM/DD/YYYY', new CultureInfo("en-US")).ToString("yyyy-MM-dd")