ISNULL 日期 月份
我有两个下拉列表,一个包含月份,另一个包含年份。用户选择他们想要检索的项目的提交月份和年份。在数据库中,完整输入日期,例如。 2009 年 1 月 12 日。下拉列表中有一个“所有年份”和“所有月份”选项,但当用户选择其中一个时,他们会得到空结果。非常感谢。这是我的查询:
SELECT ItemID, YEAR(Submit) AS SubmitYear, MONTH(Submit) AS SubmitMonth
FROM Items
WHERE (YEAR(Submit) LIKE ISNULL(@YearPay, ''))
AND (MONTH(Submit) LIKE ISNULL(@MonthPay, ''))
我的参数是:
<
asp: ControlParameter ControlID="DropDownList2" DefaultValue="" Name="MonthPay" PropertyName="SelectedValue" />
I have two dropdownlists, one with months and the other one with year. The user selects the submit month and year for the items they want to retrieve. In database the date is entered in full eg. 01/12/2009. There is an option for "All years" and "All months" in the dropdown lists but when users choose either they get null results. Many thanks. This is my query:
SELECT ItemID, YEAR(Submit) AS SubmitYear, MONTH(Submit) AS SubmitMonth
FROM Items
WHERE (YEAR(Submit) LIKE ISNULL(@YearPay, ''))
AND (MONTH(Submit) LIKE ISNULL(@MonthPay, ''))
My parameter are:
<asp:ControlParameter ControlID="DropDownList1" DefaultValue="" Name="YearPay" PropertyName="SelectedValue" />
<asp:ControlParameter ControlID="DropDownList2" DefaultValue="" Name="MonthPay" PropertyName="SelectedValue" />
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是解决该问题的一种方法:
这样,如果您为任一变量传递 NULL,则 WHERE 子句的该部分将返回 true。
Here's one way to solve the problem:
That way, if you pass in NULL for either variable, that part of the WHERE clause will return true.
一种相当快速的方法是确保 @YearPay 和 @MonthPay 是 INTEGER 数据类型,然后传入(例如)-1 来指示“ALL”,因此您的查询将变为:
但是,为了整体性能,我个人会避免使用以这种方式执行此操作,使用 YEAR() 和 MONTH() 因为您不会获得良好的索引使用率。相反,我很想将查询更改为仅接受日期范围,从而由 .NET 代码根据所选的下拉项生成起始日期和起始日期。
例如
,使用以下示例进行月/年选择:
2009 年 1 月将导致 @FromDate = '2009-01-01'、@ToDate - '2009-02-01'
2009 年的任何月份都会导致 @FromDate = '2009-01-01'、@ToDate = '2010-01-01'
任何月份、任何年份都会产生 = @FromDate = NULL, @ToDate = NULL
One fairly quick way is to make sure @YearPay and @MonthPay are INTEGER datatypes, then pass in (e.g.) -1 to indicate "ALL", so your query would become:
However, for overall performance, I'd personally steer away from doing it in this way, using YEAR() and MONTH() as you won't get good index usage. Instead, I'd be tempted to change the query to just accept a date range, whereby the to and from dates are generated by your .NET code based on the selected dropdown items.
e.g.
So, using the following examples for month/year selections:
Jan 2009 would result in @FromDate = '2009-01-01', @ToDate - '2009-02-01'
Any month, 2009 would result in @FromDate = '2009-01-01', @ToDate = '2010-01-01'
Any month, any year would result = @FromDate = NULL, @ToDate = NULL
尝试这个
和这个
话虽这么说,我完全同意 Nebakanezer 的评论(和解决方案)。
Try this
and this
That being said, I totally agree with Nebakanezer's comment (and solution).