经典ASP - 转换脚本以使用导致问题的参数

时间:2012-01-18 05:06:00

标签: sql asp-classic

我有一个非常大的搜索脚本,直到现在才进行参数化(虽然受到正则表达式函数的半保护并且不向公众开放),但刚刚转换它,我遇到了一些问题我以前用来获取记录数的方式。

这是我的脚本的一个示例,在参数化之前:

selectClause = "SELECT column FROM table "
whereClause = "WHERE something = 'something' "

If something = "someCondition" Then
whereClause = whereClause & "AND something = '"&input&"' "
End If

If somethingElse = "someOtherCondition" Then
whereClause = whereClause & "AND somethingElse = '"&input&"' "
End If

' ... plus loads more conditional statements...

orderClause = "ORDER BY something DESC "

' get the total number of records, which is now what I am stuck on ////

SQL = " SELECT COUNT(*) AS total FROM ("&selectClause & whereClause&") AS Q1; "
Set rs = Conn.Execute(SQL)
If NOT rs.EOF Then
Session("record-count") = rs.Fields("totalRecords")
End If
rs.Close

' calculate paging and limitClause

... some code
limitClause = limit 0, 20 ' example

' build query

SQL = selectClause & whereClause & orderClause & limitClause

Conn.Execute(SQL)

除了对攻击持开放态度之外,这种情况还算不错。所以我开始使用参数转换它,但现在我无法弄清楚如何获得总计数而不必再次编写整个搜索查询,这是我的示例(上图)长度的30倍。希望我的代码能够更好地解释我的情况。

selectClause = "SELECT column FROM table "
whereClause = "WHERE something = 'something' "

If something = "someCondition" Then
whereClause = whereClause & "AND something = ? "
Set newParameter = cmdConn.CreateParameter("@blah1", ad_varChar, ad_ParamInput, Len(input), Replace(input,"'","\'"))
cmdConn.Parameters.Append newParameter
End If

If somethingElse = "someOtherCondition" Then
whereClause = whereClause & "AND somethingElse = ? "
Set newParameter = cmdConn.CreateParameter("@blah2", ad_varChar, ad_ParamInput, Len(input), Replace(input,"'","\'"))
cmdConn.Parameters.Append newParameter
End If

orderClause = "ORDER BY something DESC "

' but now the whereClause contains ?'s which cannot be used here, which has confused me on how I should be getting the new count.
' /////////////////////////////
SQL = " SELECT COUNT(*) AS total FROM ("&selectClause & whereClause&") AS Q1; "
Set rs = Conn.Execute(SQL)
If NOT rs.EOF Then
Session("record-count") = rs.Fields("totalRecords")
End If
rs.Close
' /////////////////////////////

' calculate paging and limitClause

... some code
limitClause = "limit x, y;"

' build query

SQL = selectClause & whereClause & orderClause & limitClause

cmdConn.CommandText = SQL

正如您所看到的,我不能使用之前使用的count方法,因为where子句包含?',这意味着特定计数查询需要自己的参数集合。任何人都可以建议我如何在不必复制这个巨大查询的情况下获得我的计数吗?

猜测一下,我可能会创建另一个命令对象cmdConn2,并且我在其中设置了一个参数,将另一个设置为cmdConn2,然后可以将其用于计数查询,但我的猜测并不总是最好的方法。

任何帮助总是非常感谢。

1 个答案:

答案 0 :(得分:0)

基本上除了selectorder by子句之外的所有内容对于两个查询都是相同的。

因此,一个答案是:

  • 将除selectorder by子句之外的所有内容移动到子例程中。
  • select子句设置为select column from table,调用子例程进行常规处理,然后适当设置order by子句并执行SQL。
  • 然后将select子句设置为select count(*) from table,调用子例程进行公共处理,然后执行SQL(无order by子句)。

或者,您可以使用第一个查询结果中的ADO RecordSet RecordCount property之类的内容来获取返回的记录数吗?