Stop While Not when the correct answer is found - asp-classic

I've got a table with six records, so far. Everyone has 2 fields: Min_lenght, Max_lenght.
Those field define a range, so the first item has Min_lenght = 160, Max_lenght = 179 and so on.
When defining 1 value (custom_lenght) I need to stop the SQL when this values is in range.
So (custom_lenght > Min_lenght) AND (custom_lenght < Max_lenght)
custom_lenght = cint(request("custom_lenght"))
Set objRS2 = Server.CreateObject("ADODB.Recordset")
sql2 = "SELECT * FROM tbl_model where Order by ID_model ASC"
objRS2.Open sql2, ConString
If Not objRS2.EOF Then
While Not objRS2.EOF
Min_lenght = cint(objRS2("Min_lenght"))
Max_lenght = cint(objRS2("Max_lenght"))
order = objRS2("order")
Price = objRS2("price")
if (custom_lenght > Min_lenght ) AND (custom_lenght < Max_lenght) then
Outofrange="True"
else
Outofrange = "False"
End If
objRS2.MoveNext
Wend
End If
PuliziaRS(objRS2)
The problem is, the SQL browse all the records. I need to obtain the data (price and order) of the item that falls between the range

Change your SQL statement to "SELECT order, price FROM tbl_model WHERE (Min_length < " & custom_length & " AND Max_length > " & custom_length & ") ORDER BY ID_Model"
This will limit the recordset to records that match your custom_length.

As a alternative;
custom_lenght = cint(request("custom_lenght"))
Set objRS2 = Server.CreateObject("ADODB.Recordset")
sql2 = "SELECT order, price FROM tbl_model WHERE " & custom_lenght & " BETWEEN Min_lenght AND Max_lenght Order by ID_model ASC"
objRS2.Open sql2, ConString
If Not objRS2.EOF Then
order = objRS2("order")
Price = objRS2("price")
Outofrange = "True"
Else
Outofrange = "False"
End If
objRS2.Close

Related

Multiple "If Then Else" in "Do While Not" loop not working, but they do singularly

OK so here is what's pulling my hair out ! I have a page which reads records from a table in one DB, manipulates the data slightly, then writes it to another DB.
In the Do While Not EOF loop, I have a number of If Then Else statements to manipulate the data.
If I run the code in full, most of the If Then Else do not work, if I run the page with just each one in there, they work fine.
I have spent 8 hrs+ working on this and am still baffled
Dim rsndb, fieldstr1, fieldstr2, fieldstr3, fieldstr4, fieldstr5, fieldstr6, fieldstr7, fieldstr8, fieldstr9, fieldstr10, fieldstr11, fieldstr12, fieldstr13, fieldstr14, fieldstr15
recordstr = 0
'##### Empty temp table #####
Set Connection = Server.CreateObject("ADODB.Connection")
Connection.Open "DSN=website"
cSql = "DELETE FROM newtandltest"
Connection.Execute (cSql)
Connection.Close
Set Connection = Nothing
' Select Records From House Database
Set adoCon = Server.CreateObject("ADODB.Connection")
adoCon.Open "DSN=newdatabase;UID=Intranet;Pwd=password;"
Set rsndb = Server.CreateObject("ADODB.Recordset")
strSQL="Select top 500 VendorTransaction.VendorNo As propvendor, Resort.ResortCode As rid, Resort.ResortName As resname, Locations.LocationName As proploc, Country.CountryCode As propcountry, Season.SeasonDesc As propsea, Property.SeasonDesc As propextrasea, Property.Size As psize, Property.Occupancy As occ, FloatingPoints.FloatingPointsName As TAOLF, Property.StartWeek As propsw, Property.EndWeek As propew, Property.Weeks As propweeks, Property.Points As proppoints, Property.WebPricePW As webprice, Property.Priority As priority, Property.OpenToOffer As offers, Property.PoAOffer As poa, Property.RentalPW As rentalpw, Property.WebDate As webdate"
strSQL = strSQL & " From Property Inner Join Resort On Property.ResortId = Resort.Id Inner Join Country On Resort.CountryId = Country.Id Inner Join Locations On Resort.LocationId = Locations.Id Inner Join FloatingPoints On Property.FloatPointId = FloatingPoints.Id Inner Join PropertyStatus On Property.StatusId = PropertyStatus.Id Inner Join PropertyType On Property.TypeId = PropertyType.Id Inner Join Season On Property.SeasonId = Season.Id Inner Join VendorTransaction On VendorTransaction.propertyId = Property.Id Where (Property.WebDate >= DateAdd(day, -187, GetDate()) And Property.StatusId = 4 and year(Property.WebDate) <> 9999)"
rsndb.Open strSQL, adoCon
Set adoCon1 = Server.CreateObject("ADODB.Connection")
adoCon1.Open "DSN=website"
Do While not rsndb.EOF
'------------------------------------------------------------------------------------------------------------------
fieldstr1 = rsndb("webdate")
'------------------------------------------------------------------------------------------------------------------
fieldstr2 = rsndb("propvendor")
'------------------------------------------------------------------------------------------------------------------
fieldstr3 = rsndb("propcountry")
If rsndb("proploc") = "FLOR" Then
fieldstr3 = rsndb("proploc")
End If
If rsndb("proploc") = "MADE" Then
fieldstr3 = rsndb("proploc")
End If
If rsndb("propcountry") = "ESC" Then
fieldstr3 = rsndb("propcountry") & left(rsndb("proploc"),1)
End If
'------------------------------------------------------------------------------------------------------------------
resnamestr = replace(rsndb("resname"),chr(13)," ")
resnamestr = replace(rsndb("resname"),chr(34),"")
resnamestr = replace(rsndb("resname"),"'","")
fieldstr4 = resnamestr
'------------------------------------------------------------------------------------------------------------------
fieldstr5 = rsndb("propsea")
If len(rsndb("propextrasea")) > 3 Then
fieldstr5 = rsndb("propextrasea")
End If
If rsndb("propcountry") = "POIN" Then
fieldstr5 = ""
End If
'------------------------------------------------------------------------------------------------------------------
fieldstr6 = ""
'------------------------------------------------------------------------------------------------------------------
fieldstr7 = rsndb("propweeks")
If rsndb("propcountry") = "POIN" Then
fieldstr7 = rsndb("proppoints")
End If
'------------------------------------------------------------------------------------------------------------------
If rsndb("propsw") = rsndb("propew") Then
fieldstr8 = rsndb("propsw")
End If
If rsndb("propcountry") = "POIN" Then
fieldstr8 = "POINTS"
fieldstr9 = "n/a"
End If
If rsndb("propsw") < rsndb("propew") Then
fieldstr8 = rsndb("propsw") & "/" & rsndb("propew")
End If
If rsndb("TAOLF") = "F" Then
fieldstr8 = "FLOATING"
End If
'------------------------------------------------------------------------------------------------------------------
tempsize = rsndb("psize")
Select Case tempsize
Case 1
fieldstr9 = "Studio" & " - " & rsndb("occ")
Case 2
fieldstr9 = "1 Bedroom" & " - " & rsndb("occ")
Case 3
fieldstr9 = "2 Bedroom" & " - " & rsndb("occ")
Case 4
fieldstr9 = "3 Bedroom" & " - " & rsndb("occ")
Case 5
fieldstr9 = "4 Bedroom" & " - " & rsndb("occ")
End Select
'------------------------------------------------------------------------------------------------------------------
fieldstr10 = rsndb("rid")
'------------------------------------------------------------------------------------------------------------------
fieldstr11 = rsndb("rid")
'------------------------------------------------------------------------------------------------------------------
fieldstr12 = ""
'------------------------------------------------------------------------------------------------------------------
fieldstr13 = "N"
'------------------------------------------------------------------------------------------------------------------
fieldstr14 = rsndb("webprice")
If rsndb("offers") = 1 Then
fieldstr14 = "Offers"
End If
If rsndb("poa") = 1 Then
fieldstr14 = "POA"
End If
'------------------------------------------------------------------------------------------------------------------
fieldstr15 = rsndb("rentalpw")
lCount = lCount + 1
Set Connection1 = Server.CreateObject("ADODB.Connection")
Connection1.Open "DSN=website"
cSql = "INSERT INTO newtandltest(datefield, field1, field2, field3, field4, field5, field6, field7, field8, field9, field10, field11, field12, price, bargainprice)"
cSql = cSql & "VALUES('"&fieldstr1&"','"&fieldstr2&"','"&fieldstr3&"','"&fieldstr4&"','"&fieldstr5&"','"&fieldstr6&"','"&fieldstr7&"','"&fieldstr8&"','"&fieldstr9&"','"&fieldstr10&"','"&fieldstr11&"','"&fieldstr12&"','"&fieldstr13&"','"&fieldstr14&"','"&fieldstr15&"');"
Connection1.Execute (cSql)
Connection1.Close
Set Connection1 = Nothing
rsndb.MoveNext
Loop
rsndb.Close
adoCon.Close
Set rsndb = Nothing
Set adoCon = Nothing
I am with Shadow Wizard. Tidy up your code, only use rsndb once for every key. And use a dictionary to store your fields with reasonable names. As it is now, it is not maintainable: How should someone know what fieldStr12 stands for?
There is one real bug I spotted: You do three times a replace on the original string, so effectively only the last replace will be visible.
Suggestion how to tidy your code:
Do While not rsndb.EOF
Set fld = createObject("Scripting.Dictionary")
fld.Add "webdate", rsndb("webdate")
fld.Add "propvendor", rsndb("propvendor")
fld.Add "propcountry", rsndb("propcountry")
' etc...
Select Case fld("proploc")
Case "FLOR" fld("propcountry") = fld("proploc")
Case "MADE" fld("propcountry") = fld("proploc")
End case
If fld("propcountry") = "ESC" Then
fld("propcountry") = fld("propcountry") & left(fld("proploc"),1)
End If
' This part is not correct, it is only replacing the ' by an empty string
'resnamestr = replace(rsndb("resname"),chr(13)," ")
'resnamestr = replace(rsndb("resname"),chr(34),"")
'resnamestr = replace(rsndb("resname"),"'","")
'fieldstr4 = resnamestr
fld("resname") = replace(fld("resname"), chr(13), " ")
fld("resname") = replace(fld("resname"), chr(34), "")
fld("resname") = replace(fld("resname"), "'", "")
' etc...
Set Connection1 = Server.CreateObject("ADODB.Connection")
Connection1.Open "DSN=website"
cSql = "INSERT INTO newtandltest(datefield, field1, field2, field3, field4, field5, field6, field7, field8, field9, field10, field11, field12, price, bargainprice)"
' the Items property of a dictionary is an array in the same order that you add them to the dictionary
' You could do the same with the Keys property.
cSql = cSql & "VALUES('" & join(fld.Items, "','") & "');"
Connection1.Execute (cSql)
Connection1.Close
Set Connection1 = Nothing
rsndb.MoveNext
Loop
Something u can improve in your code.
1) You have open connection before while loop so you do not need to open it again in While loop it should be remove
Set Connection1 = Server.CreateObject("ADODB.Connection")
Connection1.Open "DSN=website
While loop ...
WEND
Connection1.Close
Set Connection1 = Nothing
2) check Null and blank before replacing with some value.
for e.g
if(fld("resname") <> "" AND NOT ISNULL(fld("resname")))
replace(fld("resname"), chr(13), " ")
end if
- Note track loop with default value like response.write ("hello") and check in which row loop is breaking and by which cause
The only thing that I can see that might cause this is reading the same field more than once; with certain types of fields (e.g. Memo field of Access) it might become blank after the first read.
To fix such problem you need to read each field once, and store it into local variable:
Do While not rsndb.EOF
curPropLoc = rsndb("proploc")
curPropCountry = rsndb("propcountry")
'...
fieldstr3 = curPropCountry
If curPropLoc = "FLOR" Then
fieldstr3 = curPropLoc
End If
If curPropLoc = "MADE" Then
fieldstr3 = curPropLoc
End If
'...keep using curPropLoc instead of rsndb("proploc") throughout the loop...
'...keep using curPropCountry instead of rsndb("propcountry") throughout the loop...
'......
rsndb.MoveNext
Loop

query string in classic asp code to catch integer values

I have written below code piece that is supposed to search from DB based on two Parameters
Integer value(ID of a SHIP)
String value(SHIP name).
But with the following code I am able to get data from the DB using the SHIP name i.e using the 2nd case. But unable to search the data using the ID of the SHIP.
Following is the code snippet. Any help on these is highly appreciated.
nIMO = sql_ship_friendly(request.querystring("nIMO"))
if IsNumeric(nIMO) = false then
nIMO = ""
else
nIMO = cInt(nIMO)
end if
sVessel = sql_ship_friendly(UCase(request.querystring("sVessel")),10)
if not nIMO = "" then
'search based on vessel id
sql = "SELECT IMO_NBR, VESSEL_NM, COALESCE(SHIP_TYP,'0') AS SHIP_TYP, COALESCE(DWT_WT, 0) AS DWT_WT, COALESCE(YEAR_BUILT_NBR, 0) AS YEAR_BUILT_NBR FROM RSP_VESSEL_VW WHERE ACTIVE_IND='Y' AND IMO_NBR = 7723948"
Set db1 = Server.CreateObject("ADODB.Connection")
db1.Open GV_VIEW_DB_String
Set rs = db1.Execute(sql)
Set dbl = nothing "
elseif not sVessel = "" then
'search based on vessel number
sql = "SELECT IMO_NBR, VESSEL_NM, COALESCE(SHIP_TYP,'0') AS SHIP_TYP, COALESCE(DWT_WT, 0) AS DWT_WT, COALESCE(YEAR_BUILT_NBR , 0) AS YEAR_BUILT_NBR FROM RSP_VESSEL_VW WHERE VESSEL_NM LIKE '"&SVESSEL&"%' AND ACTIVE_IND='Y'"
' response.write sql Set db1 =
Server.CreateObject("ADODB.Connection") db1.Open GV_VIEW_DB_String
Set rs = db1.Execute(sql) Set dbl = nothing
if your first case you have placed following
sql = "SELECT IMO_NBR, VESSEL_NM, COALESCE(SHIP_TYP,'0') AS SHIP_TYP,
COALESCE(DWT_WT, 0) AS DWT_WT, COALESCE(YEAR_BUILT_NBR, 0) AS
YEAR_BUILT_NBR FROM RSP_VESSEL_VW WHERE ACTIVE_IND='Y' AND IMO_NBR =
7723948"
but I can see you are using the nIMO perameter in query. Put it and you should get result..
You can use it like AND IMO_NBR = nIMO or likewise.
The problem is there is no where on your SQL statement that use nIMO variable as your search criteria. Forget about using IsNumeric(nIMO) = false... Use isNull function instead. Try this.
if not isnull( request.querystring("nIMO")) then
nIMO = cInt(nIMO)
sql = "SELECT IMO_NBR, VESSEL_NM, COALESCE(SHIP_TYP,'0') AS SHIP_TYP," &_
"COALESCE(DWT_WT, 0) AS DWT_WT, COALESCE(YEAR_BUILT_NBR, 0) AS " &_
"YEAR_BUILT_NBR FROM RSP_VESSEL_VW WHERE ACTIVE_IND='Y' AND " &_
"IMO_NBR =" & nIMO
...
...
...
end if

nested select statements taking too long to load on SQL server

I have a page that displays reports on a grid. The grid uses an Object data source which is bound to a class that returns data. The class itself uses standard SQL query to return a count of records and binds to a dataview. The issue we are having is that it takes about 10 minutes sometimes to load and I know there has to be a better way but cannot for the life of me, figure out what. Hoping to get some insights from anyone on how to optimize this for performance. The data class is shown below: any feedback would be appreciated. There are about 650 attorneys returned by the attorney view which is bound to 2 tables: attorneys and locations table. The view on which the counts are performed on is bound to 2 tables also: current cases and previous cases tables and that returns about 125,000 cases total. Caching is out of the question because the end user will be able to supply any start and end dates to generate the report.
Dim PendingStringBuilder As String = "((dbo.cases.attorney_id = dbo.attorneys.att_id) AND (dbo.cases.date_assigned <= #StartDate) AND (dbo.cases.closing_date >= #StartDate OR dbo.cases.closing_date IS NULL)) OR ((dbo.casepreviousattorneys.attorney_id =
dbo.attorneys.att_id) AND (dbo.casepreviousattorneys.previous_assignment_date <= #StartDate) AND (dbo.casepreviousattorneys.unassignment_date >= #StartDate OR dbo.casepreviousattorneys.unassignment_date IS NULL))"
Dim AssignedStringBuilder As String = "((dbo.cases.attorney_id = dbo.attorneys.att_id) AND (dbo.cases.date_assigned >= #StartDate) AND (dbo.cases.date_assigned <= #EndDate)) OR ((dbo.casepreviousattorneys.attorney_id = dbo.attorneys.att_id) AND (dbo.casepreviousattorneys.previous_assignment_date
>= #StartDate) AND (dbo.casepreviousattorneys.previous_assignment_date <= #EndDate))"
Dim CountTable As String = " dbo.cases WITH (NOLOCK) INNER JOIN dbo.tlkpcasetype ON dbo.cases.case_type_id = dbo.tlkpcasetype.case_type_id FULL OUTER JOIN dbo.casepreviousattorneys ON dbo.cases.case_no = dbo.casepreviousattorneys.case_no"
Dim dt As New DataTable("ReportTable")
Dim dr As DataRow
dt.Columns.Add("CasesPending", Type.[GetType]("System.Int32"))
dt.Columns.Add("CasesAssigned", Type.[GetType]("System.Int32"))
dt.Columns.Add("ProbationViolation", Type.[GetType]("System.Int32"))
dt.Columns.Add("BailOnly", Type.[GetType]("System.Int32"))
dt.Columns.Add("TotalCases", Type.[GetType]("System.Int32"))
dt.Columns.Add("AttorneyID", Type.[GetType]("System.Int32"))
dt.Columns.Add("AttorneyName", Type.[GetType]("System.String"))
dt.Columns.Add("AttorneyFirstName", Type.[GetType]("System.String"))
dt.Columns.Add("AttorneyLastName", Type.[GetType]("System.String"))
dt.Columns.Add("UnitID", Type.[GetType]("System.Int32"))
dt.Columns.Add("UnitName", Type.[GetType]("System.String"))
dt.Columns.Add("UnitType", Type.[GetType]("System.String"))
dt.Columns.Add("OfficeID", Type.[GetType]("System.Int32"))
dt.Columns.Add("Office", Type.[GetType]("System.String"))
If cn.State = ConnectionState.Closed Then cn.Open()
Dim cmd As SqlCommand
Dim rdr As SqlDataReader
strSQL = "SELECT DISTINCT dbo.attorneys.user_id, dbo.attorneys.att_id AS AttorneyID, dbo.attorneys.first_name +' '+ dbo.attorneys.last_name AS AttorneyName, dbo.attorneys.unit_id AS UnitID, dbo.tlkpunit.unit AS UnitName, dbo.tlkpunit.unit_type AS UnitType,
dbo.tlkpunit.office_id AS OfficeID, dbo.tlkpoffice.office AS Office, "
strSQL += "(SELECT COUNT(DISTINCT dbo.cases.case_no) AS ExprCasesPending FROM " & CountTable & " WHERE (" & PendingStringBuilder & ")) As CasesPending, "
strSQL += "(SELECT COUNT(DISTINCT dbo.cases.case_no) AS ExprCasesAssigned FROM " & CountTable & " WHERE (dbo.tlkpcasetype.case_type <> 'Probation Violation') AND (dbo.tlkpcasetype.case_type <> 'Bail Only') AND (" & AssignedStringBuilder & ")) As CasesAssigned,
"
strSQL += "(SELECT COUNT(DISTINCT dbo.cases.case_no) AS ExprProbationViolation FROM " & CountTable & " WHERE (dbo.tlkpcasetype.case_type = 'Probation Violation') AND (" & AssignedStringBuilder & ")) As ProbationViolation, "
strSQL += "(SELECT COUNT(DISTINCT dbo.cases.case_no) AS ExprBailOnly FROM " & CountTable & " WHERE (dbo.tlkpcasetype.case_type = 'Bail Only') AND (" & AssignedStringBuilder & ")) As BailOnly, "
strSQL += "(SELECT COUNT(DISTINCT dbo.cases.case_no) AS ExprTotalCases FROM " & CountTable & " WHERE (" & AssignedStringBuilder & ")) As TotalCases "
strSQL += " FROM dbo.attorneys WITH (NOLOCK) LEFT OUTER JOIN dbo.tlkpunit ON dbo.attorneys.unit_id = dbo.tlkpunit.unit_id LEFT OUTER JOIN dbo.tlkpdivision ON dbo.tlkpunit.division_id = dbo.tlkpdivision.division_id LEFT OUTER JOIN dbo.tlkpoffice ON dbo.tlkpunit.office_id
= dbo.tlkpoffice.office_id WHERE (dbo.tlkpunit.unit <> 'test-unit') "
cmd = New SqlCommand(strSQL, cn)
cmd.Parameters.AddWithValue("#StartDate", DateAStart)
cmd.Parameters.AddWithValue("#EndDate", DateAEnd)
rdr = cmd.ExecuteReader()
While rdr.Read
If rdr("CasesPending").ToString = 0 And rdr("CasesAssigned") = 0 And rdr("ProbationViolation").ToString = 0 And rdr("BailOnly") = 0 Then
'Do not add record
Else
dr = dt.NewRow()
dr("CasesPending") = CInt(rdr("CasesPending"))
dr("CasesAssigned") = CInt(rdr("CasesAssigned"))
dr("ProbationViolation") = CInt(rdr("ProbationViolation"))
dr("BailOnly") = CInt(rdr("BailOnly"))
dr("TotalCases") = CInt(rdr("TotalCases"))
dr("AttorneyID") = rdr("AttorneyID")
dr("AttorneyName") = rdr("AttorneyName")
dr("UnitID") = rdr("UnitID")
dr("UnitName") = rdr("UnitName")
dr("UnitType") = rdr("UnitType")
dr("OfficeID") = rdr("OfficeID")
dr("Office") = rdr("Office")
dt.Rows.Add(dr)
End If
End While
rdr.Close()
cmd.Dispose()
If cn.State = ConnectionState.Open Then cn.Close()
Dim dv As New DataView(dt)
dv.Sort = "AttorneyName ASC"
Return dv
Read up on "sql execution plans" and you may want to review your table indexes. It is likely that these things will yield the greatest results. See this SQL Server Optimization MSDN article for more information.
I also notice in your VB code you are not parameterizing your SQL string. You should consider doing this after the above for additional performance benefit.
For more information on using SQL parameters see:
http://www.codinghorror.com/blog/2005/04/give-me-parameterized-sql-or-give-me-death.html
http://technet.microsoft.com/en-us/library/ms186219.aspx
Try using a stored procedure. This will have the code compiled in the Sql Server already and the execution plan stored ahead of time. John

Copy records to another recordset using Active Server Page

I'm programming in Classic ASP. I'm trying to do the paging. My backend is SQL CE 3.5. Unfortunetly, it doesn't support paging in SQL Query (Like row_number() in sql server).
So I go with ASP Paging. But when i ask to the recordset, give me the first 10 records by setting the rs.PageSize and rs.AbsolutePage and all, it gives me all records. So I planned to copy only first 10 rows from the resultant recordset to another new recordset. So I coded like below:
Set rsTemp = CopyRecordsetStructure(objRs)
rsTemp.Open
iRecordsShown = 0
Set objFields = objRs.Fields
intFieldsCount = objFields.Count-1
Do While iRecordsShown < intPageSize And Not objRs.EOF
rsTemp.AddNew
For Idx = 0 To intFieldsCount
rsTemp.Fields(Idx).Value = objRs.Fields(Idx).Value
Next
rsTemp.Update
iRecordsShown = iRecordsShown + 1
objRs.MoveNext
Loop
Public Function CopyRecordsetStructure(ByVal rs)
Dim rsTemp
Set rsTemp = CreateObject("ADODB.Recordset")
Set objFields = rsTemp.Fields
intFieldCount = objFields.Count - 1
For Idx = 0 To intFieldCount
rsTemp.Fields.Append objFields(Idx).Name, _
objFields(Idx).Type, _
objFields(Idx).DefinedSize
Next
Set CopyRecordsetStructure = rsTemp
End Function
The issue is i could not open the" rsTemp". It throws me error
The connection cannot be used to perform this operation. It is either closed or invalid in this context.
If I use some dummy query and connection it doesn't work.
Please help to copy the records from one recordset to another new record set.
Thanks in advance
Ganesh.
Not sure, but this looks wrong
Set objFields = rsTemp.Fields
Shouldn't it be
Set objFields = rs.Fields
With the comments and fixed in the above comments, the function should be updated Set objFields = rs.Fields to:
Usage:
Dim rsTemp
Set rsTemp = CopyRecordset(rsPadicon)
Update Code
Public Function CopyRecordset(rs)
Dim rsTemp, objFields, intFieldsCount, intPageSize
Set rsTemp = CopyRecordsetStructure(rs)
rsTemp.Open
Set objFields = rs.Fields
intFieldsCount = objFields.Count-1
response.write("<li> rs.RecordCount :" & rs.RecordCount & "</li>")
' response.write("<li> intFieldsCount :" & intFieldsCount & "</li>")
rs.MoveFirst
Do While Not rs.EOF
rsTemp.AddNew
Dim i
For i = 0 to intFieldsCount 'use i as a counter
' response.write("<li> Name :" & rs.Fields(i).Name & "</li>")
' response.write("<li> Value :" & rs.Fields(i).Value & "</li>")
if Not IsNull(rs.Fields(i).Value) then
rsTemp.Fields(i).Value = rs.Fields(i).Value
End if
Next
rsTemp.Update
rs.MoveNext
Loop
Set CopyRecordset = rsTemp
End Function
Public Function CopyRecordsetStructure(ByVal rs)
Dim rsTemp, objFields, intFieldCount, Idx
Set rsTemp = CreateObject("ADODB.Recordset")
Set objFields = rs.Fields
intFieldCount = objFields.Count - 1
For Idx = 0 To intFieldCount
rsTemp.Fields.Append objFields(Idx).Name, _
objFields(Idx).Type, _
objFields(Idx).DefinedSize
Next
Set CopyRecordsetStructure = rsTemp
End Function

how to count records in ASP classic?

I'm not quite familiar with programming ASP classic. I just need a small code to run on my webpage. How do i count the record of the returned query?
<%
Set rsscroll = Server.CreateObject("ADODB.Recordset")
Dim strSQLscroll, rsscroll
strSQLscroll = "SELECT * FROM tblItems where expiration_date > getdate() order by expiration_date desc;"
rsscroll.open strSQLscroll,oConn
%>
thanks,
It is possible (but not recommended) to use the RecordCount property on the Recordset object as follows:
iTotalRecords = rsscroll.RecordCount
If your table is really large, this can take a long time to run. I would instead run a separate SQL query to get the total records
SQL = "SELECT COUNT(*) AS TotalRecords FROM tblItems WHERE expiration_date > getdate() "
set rsRecordCount = conn.Execute(SQL)
if not rsRecordCount.Eof then
iTotalRecords = rsRecordCount.Fields("TotalRecords")
else
iTotalRecords = 0
end if
rsRecordCount.Close
set rsRecordCount = nothing
rsscroll.RecordCount
One simple solution's to use the SQL COUNT method. This assumes you want the number of rows and not the data itself.
<%
Set rsscroll = Server.CreateObject("ADODB.Recordset")
Dim strSQLscroll, rsscroll, intRow
strSQLscroll = "SELECT COUNT(*) AS Total FROM tblItems WHERE expiration_date > getdate();"
rsscroll.open strSQLscroll, oConn
response.write rsscroll("Total")
rsscroll.close: set rsscroll = nothing
oConn.close: set oConn = nothing
%>
This returns one row with a single value called "Total." (Read on if you need both the row count and data.)
Your query code uses a default RecordSet, which returns data in "forward-only" mode for efficiency. It'll step through row-by-row, but doesn't know the actual count. (This mode also sets the RecordSet.RecordCount to -1, so the field isn't useful for you.)
RecordSet.Open's "Cursor Type" parameter lets you change to "Keyset" mode (parameter value 1), which does set the RecordCount field to the number of data rows. ("Lock Type" and "Command Type" parameters included for completeness, but they don't figure into this answer.)
RecordsetObject.Open "TableName|SQLStatement", ConnectionObject [,Cursor Type] [,Lock Type] [,Command Type]
Add this parameter to your code's RecordSet.Open call and then check RecordCount.
<%
Set rsscroll = Server.CreateObject("ADODB.Recordset")
Dim strSQLscroll, rsscroll, intRow
strSQLscroll = "SELECT * FROM tblItems where expiration_date > getdate() order by expiration_date desc;"
rsscroll.open strSQLscroll, oConn, 1
intRow = rsscroll.RecordCount
' ... do something with intRow
rsscroll.close: set rsscroll = nothing
oConn.close: set oConn = nothing
%>
If database performance means anything to your situation, the RecordSet.GetRows() method's much more efficient.
<%
Dim rsscroll, intRow, rsArray
Set oConn = CreateObject("ADODB.Connection")
oConn.open "<connection string>"
strSQLscroll = "SELECT * FROM tblItems where expiration_date > getdate() order by expiration_date desc"
Set rsscroll = conn.execute(strSQLscroll)
if not rsscroll.eof then
rsArray = rsscroll.GetRows()
intRow = UBound(rsArray, 2) + 1
response.write "rows returned: " & intRow
' ... do any other operations here ...
end if
rsscroll.close: set rsscroll = nothing
oConn.close: set oConn = nothing
%>
I usually use a separate query like "select count(*) from table " to get counts because I usually need not only the count but a summation of the number of units or the average price or whatever and it's easier to write a separate query than to make more variables and say "TotalUnits = TotalUnits + rs("Units").value" inside the loop to display the results. It also comes in handy for the times you need to show the totals above the results and you don't want to loop though the recordset twice.
Get in the habbit of storing returned data in arrays. This is amazingly faster to iterate than using an open record set. Also, specify the fields to select when doing this as you have to explicitly reference the array index.
<%
Set rsscroll = Server.CreateObject("ADODB.Recordset")
Dim strSQLscroll, rsscroll
Dim arrCommon
'Open recordset, copy data to array
strSQLscroll = "SELECT field1, field2, field3 FROM tblItems where expiration_date > getdate() order by expiration_date desc;"
rsscroll.open strSQLscroll,oConn
arrCommon = rsscroll.getRows()
rsscroll.close
'Get the total records in this array
response.write ubound(arrCommon, 2);
'Loop...
for i = 0 to ubound(arrCommon, 2)
' This prints field 3
response.write arrCommon(2, i)
next
%>
You could just change your SQL to count the records:
strSQLscroll = "SELECT count(*) as Total FROM tblItems where expiration_date > getdate();"
Then you just need to response.write rsscroll("Total")
<%
' TableID = your tables ID...
Set rsscroll = Server.CreateObject("ADODB.Recordset") Dim strSQLscroll, rsscroll strSQLscroll = "SELECT *,(SELECT TableID FROM tblItems where expiration_date > getdate()) As Count FROM tblItems where expiration_date > getdate() order by expiration_date desc;"
rsscroll.open strSQLscroll,oConn
Count = rsscroll("Count")
%>
You can try this
Dim count
count = 0
if strSQLscroll.eof <> true or strSQLscroll.bof <> true then
while not strSQLscroll.eof
count = count+1
strSQLscroll.movenext
wend
end if
response.write(count)
If you are using MySQL try this:
Dim strSQLscroll, rsscroll, countrs
Set rsscroll = Server.CreateObject("ADODB.Recordset")
rsscroll.CursorLocation = 3
rsscroll.open "SELECT * FROM tblItems where expiration_date > getdate()
order by expiration_date desc;",oConn
countrs = rsscroll.recordcount

Resources