Code won't execute after recordset returns using if-statement - asp-classic

Can anyone help me explain the following problem
In a SQL-query I get info about the occurrence of an id from another table.
Everything works here and I show a crucial snippet below
set rsRecordCount = Cn.execute(mysql_query)
dim cnt
cnt = rsRecordCount("TotalRecords")
response.write("cnt " & cnt & " id = " & id & "<br>")
rsRecordCount.Close
set rsRecordCount = nothing
So - via response.write I get info about the occurrence. The problem arises
when I want to test the cnt variable
if cnt = 0 then
response.write(".....<br>")
end if
just a simple test, the code stops execute here and I wonder why? I first thought cnt might work like a pointer pointing to a recordset and when setting it to null it would be error or undefined behaviour? But I've tried to comment out .Close and = nothing. The problem is still there.
Its really the cnt that is the prolem, If I use antoher variable - the code works again
if blablabla = 0 then
response.write("it works now<br>")
end if
How do I get around this/what did I miss
thanks!!!

I first thought cnt might work like a pointer pointing to a recordset
You were right in this assumption, but not 100% accurate. The default property of Recordset object returns a Field object, i.e. after this line:
cnt = rsRecordCount("TotalRecords")
The variable cnt is actually a Field object. Now you ask, why this line "works"?
response.write("cnt " & cnt & " id = " & id & "<br>")
That's because the Field object returns its Value property when being treated as a String.
However, when trying to compare to integer, VBScript fails to find any proper conversion and chokes.
There are two common ways to solve such a thing:
Convert the value to integer using CInt or CLng:
cnt = CLng(rsRecordCount("TotalRecords"))
Like the Response.Write above, this one first converts to String, then to Long. Profit.
Take the actual value, not the Field object:
cnt = rsRecordCount.Fields("TotalRecords").Value
Personally, I think the second way is more elegant and readable. Both ways work. Good luck!

Related

The multi-part identifier could not be bound error won't fix

The Variable fileName contains the name of two columns to fetch value of it, which is in the type of "email,address"
The output of the fileName variable is sam#gmail.com102streetN, which is what I need
but when I try to insert that value into another column table then it throws me an error
The multi-part identifier "sam#gmail.com102streetN" could not be bound.
I don't know how to fix it
for each a in idParase
strSQL = "Select Award, Year, ("&fileName&") as dynamicColumns FROM dbo.Awards_TABLE Where awardID = "&a&""
cmdCRProc.CommandText = strSQL
Set rsCR = cmdCRProc.Execute
nameParase = rsCR("dynamicColumns")
sql2 = "Insert Into dbo.Queue (Award,Year,awardID,FileName) Values ("&rsCR(0)&", "&rsCR(1)&", "&a&", "&nameParase&") "
cmdCRProc.CommandText = sql2
Set rsCR = cmdCRProc.Execute
next
I think this isn't going wrong in the INSERT, but in the SELECT.
If I write out your SELECT it would be something this I think (I don't know the value of "a", but let's say it's 2):
Select Award, Year, (sam#gmail.com102streetN) as dynamicColumns FROM dbo.Awards_TABLE Where awardID = 2
I very much doubt you have a column named 'sam#gmail.com102streetN', right?
I don't know what your goal is, but it seems like you're building a query with a dynamic column name that doesn't exist.
What you can do is Response.Write() your SQL statements and see what the result is. Then maybe run them in your database management tool to check what's going on:
Response.write(strSQL)
And
Response.write(sql2)

Corona SQLIte : Checking if a value exists or not

I would like to check if a value can be returned or not by my SQL request:
Search_IDItem = "SELECT * FROM giftshop WHERE id ="..item_id..""
for row_2 in db:nrows(Search_IDItem) do (..)
CheckInventory = "SELECT * FROM inventory WHERE code ="..row_2.code..""
if CheckInventory ~= nil then
print(row_2.code)
updateItemsCode(row_2.code, "inventory", "qtyoninventory", row_2.qtyoninventory+1)
else
insertInventory(2,row_2.code, row_2.name, row_2.src, row_2.desc, "no",row_2.qtyoninventory,row_2.price,row_2.usetxt)
end
The error is:
near "=": syntax error
Basicly, I would like to know if the value exist, I'll only update the field "quantity", if not, I will create the new item.
Unfortunately, it doesn't work! Is there any advice or solution?
Syntax error is a result of misunderstanding of your query by the SQL.
One of the most often reasons is incorrect string insertion. So I suppose that row_xx.code is a string
To solve the problem you should "quote" row_xx.code by ' symbol like this:
CheckInventory = "SELECT * FROM inventory WHERE code ='"..row_2.code.."'"
Update
To solve the second part of the problem and figure out if value exists I suggest following
In old good plain Java when I get SQLite Cursor I may check if it has rows at all like this:
if(cursor.moveToFirst())
// it has at least one value
else
// it hasn't values at all
Sure there is similar thing for Corona
You also may use following approach to update record (creating if not exists):
// create record IF NOT EXISTS:
String createNonExistentRec = "Insert or ignore into "...// insert key/unique values
db.execSQL(createNonExistentRec, ...);
// update values:
String updateQuery = "..."
...
I found a solution :
for x in db:urows "select count(*) from inventory" do
if x>0 then -- The inventory is empty
for w in db:urows("SELECT count (*) FROM inventory WHERE code ='"..row_2.code.."'") do
--The item is already in the inventory
if w > 0 then
CheckInventory = "SELECT * FROM inventory WHERE code ='"..row_2.code.."'"
for row_4 in db:nrows(CheckInventory) do
updateItemsCode(row_4.code, "inventory", "qtyoninventory", row_4.qtyoninventory+1)
end
else
--The item is not in the inventory, so we add it!
for maxid in db:urows("SELECT MAX(id) FROM inventory") do
insertInventory(maxid+1,row_2.code, row_2.name, row_2.src, row_2.desc, "no",1,row_2.price,row_2.usetxt)
end
end
end
else
insertInventory(1,row_2.code, row_2.name, row_2.src, row_2.desc, "no",1,row_2.price,row_2.usetxt)
end
end

Filtered ADO recordset Do While Not not going in order

For some reason when I filter a record set and then start a Do While Not loop, the loop goes through even records first, then odd...
For example, the code below:
sql="SELECT * FROM ProcSaleQueue WHERE Num = '" & salegrouprs("Num") & "' AND Abbr = '" & salegrouprs("Abbr") & "' AND Item_Id = '" & salegrouprs("Item_Id") & "' AND Complete IS NULL ORDER BY ProcSaleId"
salesrs.Open sql, conn,3,3
salesrs.Filter="Complete = NULL"
salesrs.MoveFirst
Do While Not salesrs.EOF
msgbox salesrs("ProcSaleId")
'I do some processing things in here.
salesrs("Complete") = 1
salesrs.MoveNext
Loop
Will output
72
74
73
75
Instead of
72
73
74
75
But when I remove:
salesrs.Filter="Complete = NULL"
The output is in order. I'm using .Filter instead of querying again because I have to loop through this recordset multiple times and it's a huge set so I don't want too many hits to the SQL server. Any ideas?
By setting complete to 1 the record no longer is in scope of the filter, so you are on the next record. Try dropping the salesrs.MoveNext
Otherwise drop the filter all together and do a check if Complete
if salesrs("Complete") = 1 then
salesrs.MoveNext
else
'do your stuff
salesrs("Complete") = 1
end if
Your .Filter() is meaningless as you already select only the records where that field is NULL in the SQL itself.
If you want to put aside data you already processed, you can use local arrays e.g. to store ProcSaleId you can have:
Dim arrProcessedProcSaleId()
ReDim arrProcessedProcSaleId(-1)
Do While Not salesrs.EOF
curProcSaleId = salesrs("ProcSaleId")
msgbox curProcSaleId
For x=0 To Ubound(arrProcessedProcSaleId)
'Here arrProcessedProcSaleId(x) contains value of already processed ProcSaleId
Next
'I do some processing things in here.
'store value for later use:
ReDim Preserve arrProcessedProcSaleId(UBound(arrProcessedProcSaleId) + 1)
arrProcessedProcSaleId(UBound(arrProcessedProcSaleId)) = curProcSaleId
salesrs.MoveNext
Loop
salesrs.Close
Erase arrProcessedProcSaleId
You can have as many arrays as you like, if you got many records make sure to have Erase lines when done to release the memory used for the dynamic arrays.

VBScript - Database - Recordset - How to pass DateDiff value in the database

I'm using DateDiff() function of ASP to find the date difference between two dates.
The Function works fine and displays the exact date difference between two dates but when it comes to insert this value in the database it takes 9 as the value irrespect of any date difference.
Suppose difference between two dates is more than 15 or 20 days, in the database it takes "9".
I have used INT as the DATA TYPE for the column where it displaying the date difference.
Is DATA TYPE creating an issue here?
I even tried using session variable to store the value but no luck - here's my code below:
if request.Form("sub") <> "" then
sql = "Select * from emp_leave_details"
rs.open sql , con, 1, 2
dim diff
dim todate
dim fromdate
fromdate= rs("leave_from")
todate= rs("leave_to")
session("date_diff")=datediff("d",fromdate,todate)
rs.addnew
rs("emp_name") = request.Form("name")
rs("emp_no") = request.Form("number")
rs("address") = request.Form("address")
rs("contact_no") = request.Form("contact")
rs("mobile_no") = request.Form("mobile")
rs("contact_onleave") = request.Form("contact_details")
rs("leave_type") = request.Form("rad")
rs("other_leave_details") = request.Form("PS")
rs("leave_from") = request.Form("from")
rs("leave_to") = request.Form("to")
rs("applied_by") = request.Form("apply")
rs("accepted_by") = request.Form("accept")
rs("approved_by") = request.Form("approve")
rs("no_of_leave_taken")= session("date_diff")
rs.update
response.Write("<script language='javascript'>{update();}</script>")
rs.close
end if
The datatype has nothing to do with this. Storing the value in the session is not the solution. You can use a regular variable.
From your code it looks like you always use the same values for fromdate and todate. This is because you do not iterate the rows in the resultset.
if not rs.bof and not rs.eof then
do while not rs.eof
'' code to execute for each row
rs.moveNext
loop
end if
In your current script rs will always return the results of the first row returned by the query.
The second problem your running into might be the Date datatype. Convert your value to a date using cDate and use this to calculate the difference.
Your problem is , you search for "Select * from emp_leave_details" which always gives all records from that table. You retrieve the values of the first record and do a diff of these, which results in always the same value, that is normal. From your question it is unclear what you really want to do. I suppose so want so select a record like
Select * from emp_leave_details where emp_name=<%=request.Form("name")%>
and based on that add a new record with a computed no_of_leave_taken.
Sorry guys my bad...
It was the database field name that I was calling instead of
fromdate= request.form("from")
todate= request.form("to")
I was calling this
fromdate= request.form("leave_from")
todate= request.form("leave_to")
Sorry again..but I really appreciate you all for providing me with all that possible solutions.
Thanks.

Database result is passed as null unless it's read

Set rslistings = my_conn.Execute(strSQL)
Do while NOT rslistings.Eof
description = strip(rslistings("description"))
rslistings.MoveNext
loop
In strip - NULL is being passed. However, if I attach a debugger and inspect the contents of rslistings("description"), then the actual Field object is passed through
It's quite old asp code, but it works on IIS6, just not IIS7
EDIT This only happens on the "description" field with is a text type (MySQL database)
strip doesn't do a lot:
If NOT IsNull(passedinvalue) Then
// do something
Else
// do something else
If I call strip like strip(rs("description")), it is never null as the Field object is passed in. If I assign it to another value, then pass it in (like strip(mynewvar)) then the correct value is passed in.
Edit - database bits as requested below
Set my_conn = Server.CreateObject("ADODB.Connection")
Set rs = Server.CreateObject("ADODB.Recordset")
my_conn.Open "DSN=mydb"
SQL
Set rs = my_conn.Execute("SELECT description FROM table")
the Field Collection is the default member of the Recordset object.
so is the value property for the Field object.
so the following two code statements are equivalent.
Debug.Print objRs.Fields.Item(0) ' Both statements print
Debug.Print objRs(0) ' the Value of Item(0).
it is a difference if you assign a value to a variable or use it as a parameter in a function.
#Paul: If strip doesn't check if description is NULL before working on it, you could do this --
Do while NOT rslistings.Eof
description = rslistings("description")
If NOT IsNull(description) Then
description = strip(description)
Else
description = "" ' or you could have description = " "
' if you output to screen later on
End If
rslistings.MoveNext
loop

Resources