1

我有一个在 vb.net 中使用的当前 sql 查询,以获取一些返回到 datagridview 的数据。我正在检查日期时间选择器的年、月和日期,以获取从所选表返回的必要信息。我的查询工作正常,减去 case 语句部分来检查特定日期。谁能帮我解决这个查询或建议一种替代方法?

"SELECT * FROM " & Me.SelectedTable.SelectedItem.ToString & " 
WHERE(Datepart(yyyy," & colName & ") BETWEEN '" & Me.DateTimePicker1.Value.Year & "' AND '" & Me.DateTimePicker2.Value.Year & "' 
AND Datepart(mm," & colName & ") BETWEEN '" & Me.DateTimePicker1.Value.Month & "' AND '" & Me.DateTimePicker2.Value.Month & "' 
AND Datepart(dd," & colName & ") <= " & Me.DateTimePicker1.Value.Day 
& " CASE WHEN Datepart(mm," & colName & ")=" & Me.DateTimePicker1.Value.Month & " 
THEN Datepart(dd," & colName & ") = " & Me.DateTimePicker1.Value.Day & " 
WHEN Datepart(mm," & colName & ")= " & Me.DateTimePicker2.Value.Month 
& " Datepart(dd," & colName & ")= " & Me.DateTimePicker2.Value.Day & " 
ELSE Datepart(dd," & colName & ") BETWEEN 1 AND 31 END)"
4

2 回答 2

1

首先,您的查询对 SQL 注入攻击是开放的。您需要通过参数化查询来修复它。

接下来,您不需要CASE那里:您可以将您的逻辑表达为复合逻辑条件。

colName我将查询从使用由变量值定义的动态列名的查询更改col为更好的可读性。我还为来自各种选择器的值定义了参数。在查询之前,您需要在准备好的命令上设置它们。

最感兴趣的部分在底部:我将你重写CASE为一个三部分的逻辑条件,它根据 and 的设置评估三个部分之一@month1,它表示来自and@month2的月份值。DateTimePicker1DateTimePicker2

SELECT * FROM Table
WHERE (Datepart(yyyy, col) BETWEEN @year1 AND @year2
  AND Datepart(mm, col) BETWEEN @month1 AND @month2
  AND Datepart(dd, col) <= @day1
  AND (
          (Datepart(mm, col)=@month1 AND Datepart(dd, col) = @day1)
      OR  (Datepart(mm, col)=@month2 AND Datepart(dd, col) = @day2)
      OR  (Datepart(dd, col) BETWEEN 1 AND 31)
  )
于 2013-08-14T16:05:35.500 回答
0

看起来您刚刚忘记了第二个条件结束时的“THEN”。

所以,让它:

CASE 
WHEN Datepart(mm," & colName & ")=" & Me.DateTimePicker1.Value.Month & " THEN
        Datepart(dd," & colName & ") = " & Me.DateTimePicker1.Value.Day & " 

WHEN Datepart(mm," & colName & ")= " & Me.DateTimePicker2.Value.Month & " **THEN**
     Datepart(dd," & colName & ")= " & Me.DateTimePicker2.Value.Day & " 

ELSE Datepart(dd," & colName & ") BETWEEN 1 AND 31 
END
于 2013-08-14T16:05:42.193 回答