ASP - Loop while eof or bof - Select random product from idproduct but skip empty ids - random

I am trying to display a random product image and description from the access database, so i am selecting the highest idproduct then randomising a number between 1 and %highestid%, this is what i have so far....
IF frontpage = 1 then
SQLSTR = "SELECT idproduct AS prodtot FROM products order by idproduct desc"
Set objRS = Server.CreateObject("ADODB.Recordset")
SET objrs = oconn.execute(SQLSTR)
' Check result
Response.Write objRS("prodtot")
' attach
ntop = objRS("prodtot")
Randomize
' Generate random value between 1 and nTop .
nRandom= Int((nTop * Rnd) + 1)
sqlstr = "select * from products where idProduct = " & nRandom
response.Write"<br /><br />" & (sqlstr) & "<br /><br />"
'SET rs = oConn.execute(randomprod)
SET rs = oconn.execute(SQLSTR)
pranproddesc = rs("description")
response.Write(pranproddesc)
pranprodimg = rs("smallImageUrl")
end if
So far so good! But i have a problem, over time products have come and gone and I have alot of gaps in the %idproduct%, ive tried loop while rs.eof but it doesn't seem to do anythimg usefull, if anything at all. Just to clarify I have idproduct 1, 2, 5, 10, 11, 12 etc etc, so when it randomises idproduct3 it all goes up the spout! Can anyone help?
Thank you in advance! :)

Do the following:
IF frontpage = 1 then
Set objRS = Server.CreateObject("ADODB.Recordset")
SET objrs = oconn.execute(SQLSTR)
sqlSTR = "SELECT TOP 1 * FROM products ORDER BY NEWID()"
response.Write"<br /><br />" & (sqlstr) & "<br /><br />"
SET rs = oconn.execute(SQLSTR)
pranproddesc = rs("description")
response.Write(pranproddesc)
pranprodimg = rs("smallImageUrl")
end if
That sql will work in SQL Server:
Look at this page for SQL to return a random row for other databases:
http://www.petefreitag.com/item/466.cfm
Thanks, btw, I learnt something new figuring this out.

Rather than select a random ProductId, select a random row index from the recordset. That way you only have to hit the database once as well :)

Related

Query returns only 4 out of 12 values of my table. Why is this happening?

I have created a script which I am using on 2 different system. One is Windows 10 with SQL Server Express 2019 and the other is on Windows 7 (32bit) with SQL Server Express 2014. The db I am using has the same structure. The code I am using in ASP Classic is exactly the same on both machines! But in the win7 machine does not work as it should!
I am having a query to my db and the problem is that SOME of the values I am getting are empty. The code I am using is the following:
<%
Set rs21 = Server.CreateObject("ADODB.Recordset")
strSQL21 = "SELECT * FROM otherfiles WHERE animalid LIKE '" & lngRecordNo & "'
AND historyid LIKE '" & historyid & "' order by datedone DESC"
rs21.Open strSQL21, adoCon
%>
BLAH BLAH BLAH
<%
Do While not rs21.EOF
historyid = rs21("historyid")
if not historyid = "" then
Set rshis = Server.CreateObject("ADODB.Recordset")
strSQLhis = "SELECT * FROM history WHERE id_no LIKE '" & historyid & "' order by id_no DESC"
rshis.Open strSQLhis, adoCon
'------------------- if I remove the following line (Set rscol) it works fine ---------------------------
Set rscol = Server.CreateObject("ADODB.Recordset")
strcol = "SELECT * FROM hospitals WHERE id_no = "& rsGuestbook21("hosid") &" order by id_no DESC"
rscol.Open strcol, adocon
color = rscol("color")
%>
BLAH BLAH BLAH
<%=rs21("datedone")%> ---> empty value
<%=rs21("id_no")%> ---> works fine!!!
I am 100% sure that my table has its values. In fact as I mention above only but setting the rscol = Server.CreateObject("ADODB.Recordset") then the values becomes ??empty??. Commenting this line works fine.
I just figured out my ??mistake??...
Not really sure if it is a mistake thou... but the problem solved when I placed a field that had a DATA TYPE of "nvarchar(MAX)" at the end of my of my table! Weird stuff??? Do you think that there is something more than that in which I should investigate?

How to populate a data report row by row

I have to change a very old application written in Vb6 with Data Report.
Actually displays a query records with only one field named txtdata.
Now I would display always one field (txtdata) but with different text size and style depending on whether it starts with a # or not.
I thought to check records for records if it starts with # or not and set text style and size for each record.
How can I do?
Dim rs As Adodb.Recordset
Dim sql As String
Dim regtratt As
.................
' I have a Data Report with textbox named txtdata in Section1
sql = ""
sql = sql + "SELECT txtdata "
sql = sql + "FROM journal "
sql = sql + "WHERE cod=421 "
sql = sql + "ORDER BY id "
Set rs = xOpenRecordset(sql, cnOnline)
If rs.RecordCount > 0 Then
Set regtratt.DataSource = rs
regtratt.DataMember = ""
' I want to change the font according to the text but I don't know how to because DataSource=rs takes the records.
'If InStr("#", regtratt.Sections("Section1").Controls(1).Item.Value) Then
' regtratt.Sections("Section1").Controls(1).Font.size = 20
' regtratt.Sections("Section1").Controls(1).Font.Bold = True
'End If
regtratt.Orientation = rptOrientLandscape
regtratt.WindowState = vbMaximized
regtratt.Font.Name = "courier new"
regtratt.Refresh
regtratt.Show vbModal
Unload regtratt
Else
MsgBox ("Sorry No data")
End If

Populate and sort a ComboBox from another ComboBox, VBA

Hi Everyone I am having trouble getting a ComboBox to sort, when another combobox is selected.
I think I have the Right SQL Syntax but I cant seem to get the vba to run it through; currently the vba returns all of the states in the recordset regardless of the company.
Private Sub CboCountry_Click()
Set db = CurrentDb
Dim SQLStr As String
Set RsState = db.OpenRecordset("T2States", dbOpenSnapshot, dbSeeChanges)
'populates combobox with recordset, that is defined by the country input from the form
RsState.MoveFirst
Do While Not RsState.EOF
Me.CboState.RowSource = Me.CboState.RowSource & RsState("StateID") & ";" & RsState("State") & ";"
RsState.MoveNext
Loop
I think this is the right SQL String but I'm having trouble to get it to work.
'SQLStr = "SELECT T2States.StateID, T2States.States, T2States.CountryID" & _
" FROM T2States GROUP BY T2States.StatesID" & _
" WHERE T2States.CountryID = """ & Me.CboCountry.Value & """"
Any help will be greatly appreciated.
Edit#1
See Full Code below, the error that pops up when I substitute SQLStr into the Openrecordset is a Run-time error '3078' the microsoft access database engine cannot find the input table or query 'SQLStr'. Make sure it exists and that its name is spelled correctly.
What should happen is when a country is selected from CboCountry combobox, it will load the CboState combobox by sorting the recordset by CountryID
see below for both code parts
Private Sub Form_Load()
Set db = CurrentDb
Set RsCompany = db.OpenRecordset("T1Company", dbOpenDynaset, dbSeeChanges)
Set RsCountry = db.OpenRecordset("T2Countries", dbOpenSnapshot, dbSeeChanges)
Set RsAddress = db.OpenRecordset("T1Addresses", dbOpenDynaset, dbSeeChanges)
Set RsAddressType = db.OpenRecordset("T2AddressType", dbOpenSnapshot, dbSeeChanges)
Set RsCompanyAddress = db.OpenRecordset("T3Company_Address", dbOpenDynaset, dbSeeChanges)
Me.CboCountry = Null
Me.TxtAddress1 = Null
Me.TxtAddress2 = Null
Me.TxtAddress3 = Null
Me.TxtCity = Null
Me.CboAddressType = Null
Me.CboCountry = Null
Me.CboState = Null
Me.TxtPostalCode = Null
Me.TxtCompanyID = Null
Me.TxtLegalName = Null
Me.TxtNickname = Null
Me.TxtAddressID = Null
RsCountry.MoveFirst
Do While Not RsCountry.EOF
Me.CboCountry.RowSource = Me.CboCountry.RowSource & RsCountry("CountryID") & ";" & RsCountry("Country") & ";"
RsCountry.MoveNext
Loop
RsAddressType.MoveFirst
Do While Not RsAddressType.EOF
Me.CboAddressType.RowSource = Me.CboAddressType.RowSource & RsAddressType("AddressTypeID") & ";" & RsAddressType("AddressType") & ";"
RsAddressType.MoveNext
Loop
Me.TxtLegalName.SetFocus
End Sub
Private Sub CboCountry_Click()
Set db = CurrentDb
Dim SQLStr As String
'SQLStr = "SELECT T2States.StateID, T2States.State, T2States.CountryID" & _
" FROM T2States" & _
" WHERE T2States.CountryID = """ & Me.CboCountry.Value & """"
Set RsState = db.OpenRecordset("T2States", dbOpenDynaset, dbSeeChanges)
'populates combobox with recordset, that is defined by the country input from the form
RsState.MoveFirst
Do While Not RsState.EOF
Me.CboState.RowSource = Me.CboState.RowSource & RsState("StateID") & ";" & RsState("State") & ";"
RsState.MoveNext
Loop
End Sub
Let us see
1- sure you've to append with
Having T2States.States, T2States.CountryID
2- Error exist in it, extra 's' in the Column name:
GROUP BY T2States.StatesID
3- put all the code and i'll check with you what you miss.
best regards
This one turned out to be a quick fix in the Property Sheet under the DATA tab, the Row Source Type had to be changed back to 'Table/Query' from a 'Value'.
There is VBA that could account for this but it was just a simple as changing that Row Source.
The Reason for the mix up, for a quick bit of background if it helps, is that all my combo boxes are unbound and I was binding them with VBA Recordsets so the rowsource has to be a value list - Essentially the VBA is writing the list everytime it loads.
Where as when I started using SQL to generate the recordset, even though it was in VBA I had to change the property back to Table/Query.
Thanks.

Illegal Syntax. Expected valid start name character

Not sure whats gone wrong here, not very good at this stuff so apologise in advance. Ive got the below but faulting when trying to run. Not sure whats gone wrong with this part as used to work before on an older server and migrated the data across.
<%
rs.Close
if request.form () <> "" then
varSearch = replace(request.form("T1"),"*","%")
varSearch = replace(varSearch," ","%")
sql = "SELECT * FROM [Cards] WHERE [CardTypeID] = 'C' AND [Name] LIKE '%" & varSearch & "%'
ORDER BY [Name]"
rs.Source = sql
rs.Open
%>
Thanks.
request.form() - you're not capturing anything
<%
rs.Close
if request.form ("T1") <> "" then
varSearch = replace(request.form("T1"),"*","%")
varSearch = replace(varSearch," ","%")
sql = "SELECT * FROM [Cards] WHERE [CardTypeID] = 'C' AND [Name] LIKE '%" & varSearch & "%'
ORDER BY [Name]"
rs.Source = sql
rs.Open
%>

Copy one Recordset to another

Since I received so nice and fast solution to my problem, I will try again to get some help from you:
I opened two Recordsets.
Set cmd1.ActiveConnection = cn1
cmd1.CommandText = "SELECT * FROM mov Where [Date] >= #" & DateA & "#;"
Set RSold = cmd1.Execute
Set cmd2.ActiveConnection = cn2
cmd2.CommandText = "SELECT * FROM mov"
Set RSnew = cmd2.Execute
(I want to save only selected records of a file.)
I know how to copy record by record, but is there a 'Short Cut' to do it faster ?
Thanks
try this:
Dim i As Long
Do While Not RSold.EOF
' You can place if condition here
RSNew.AddNew
For i = 0 To RSold.Fields.Count - 1
RSNew.Fields(RSold.Fields(i).Name) = RSold.Fields(i).Value
Next i
RSNew.Update
RSold.MoveNext
Loop
This will copy records from RSold to RSnew recordset
You Can use code :
Set RSNew = RSOld.Clone
#user1838163 :Saving the second Recordset as a file
Dim RFileNm As String
Dim fs
Set fs = CreateObject("Scripting.FileSystemObject")
RFileNm = "c:\temp\" & Trim(RFileNm) & ".adt"
fs.DeleteFile (RFileNm)
RSNew .Save RFileNm, adPersistADTG
RSNew .Close
RSNew .Open RFileNm, , , , adCmdFile
I think this will do what you want by doing it all at once.
Dim objPB As New PropertyBag
objPB.WriteProperty "rs", RSOld
Set RSNew = objPB.ReadProperty("rs")
Set objPB = Nothing
I don't think CLONE is going to do what you want. It just gives you another view of the same recordset you already have. This allows you to use multiple bookmarks and so forth, but the recordset is still attached to the same database the original was. I also need a way to copy the recordset and save it to a new database in a new format.

Resources