1

我有一个查询如下:

select column_date, field1, field2, sum(field3) from table1
where field1 like '*xyz' and 
column_date between [please enter start date] and [please enter end date]
group by column_date, field1, field2

当我将两个参数框都留空时,输出为空白。但我希望它们输出如下

  1. 当我将两个参数框都留空时,我想显示所有记录
  2. 如果我将日期放在任何一个参数框中,它应该只显示该日期的记录
  3. 如果我将日期放在两个参数框中,它应该显示这些日期之间的所有记录。

这是我显示输出的asp代码。当我在两个文本框中插入值时它可以工作,但是如果我将其中任何一个或两个都留空,则会显示错误。

<html>
<body>
<%
dim startdate, enddate
startdate = Request.Form ("startdate")
enddate = Request.Form("enddate")
set conn = Server.CreateObject ("ADODB.Connection")
conn.open "connectionname"
set rs = Server.CreateObject ("ADODB.Recordset")
Sqlquery = "queryname '" & startdate & "', '" & enddate &'" "
rs.open sql, conn %>
<table>
<tr>
<%
For each x in rs.fields
response.write ("<th>" & x.name & "</th>") 
next %> </tr>
<tr><% Do Until rs.EOF %>
<% For each x in rs.Fields %>
<td>Response.write (x.value)</td>
<%next
rs.movenext %>
</tr>
<% loop
rs.close
conn.close %>
</table>
</body>
</html>
4

1 回答 1

1

我将从一个普通的 SELECT 查询开始找出 WHERE 子句。一旦你让它正常工作,将其转换为 GROUP BY 查询。

所以看看这个是否针对正确的记录:

PARAMETERS [Start Date] DateTime, [End Date] DateTime;
SELECT t.field1, t.field2, t.field3, t.column_date
FROM table1 AS t
WHERE
       t.field1 Like '*xyz'
    AND (         
       (t.column_date Between [Start Date] And [End Date])
    OR ([Start Date] Is Null And t.column_date = [End Date])
    OR (t.column_date = [Start Date] And [End Date] Is Null)
    OR ([Start Date] Is Null And [End Date] Is Null)
       );

假设第一个查询返回正确的行,我认为这个 GROUP BY 查询可能会给你你想要的。

PARAMETERS [Start Date] DateTime, [End Date] DateTime;
SELECT t.column_date, t.field1, t.field2, sum(t.field3)
FROM table1 AS t
WHERE
       t.field1 Like '*xyz'
    AND (         
       (t.column_date Between [Start Date] And [End Date])
    OR ([Start Date] Is Null And t.column_date = [End Date])
    OR (t.column_date = [Start Date] And [End Date] Is Null)
    OR ([Start Date] Is Null And [End Date] Is Null)
       )
GROUP BY t.column_date, t.field1, t.field2;

如果从经典 ASP 运行此查询,则需要用 ANSI 通配符替换%Access 样式的*通配符。

t.field1 Like '%xyz'

或者考虑使用ALikeANSI 通配符代替Like. 这样查询将始终以相同的方式运行,而无需切换通配符。

t.field1 ALike '%xyz'

此外,使用经典 ASP,从 ADO Command 对象运行查询,并为参数提供值。

于 2012-07-08T23:50:10.803 回答