VB6 syntax problem, "no current record" error - sql

I am writing an app in vb6 using sql server 2005. here is my current code.
Dim Sqlstring As String
Dim rstCurrentTicket As Recordset
Sqlstring = "Select SubmiterName, LastViewDate, Department, Description, Urgency, SubmitDate, ResolvedDate from TroubleTickets where Title ='" + Trim(TicketComboBox.Text) + "'"
Set rstCurrentTicket = cnnSel.OpenRecordset(Sqlstring)
NameText.Text = rstCurrentTicket!SubmiterName
DeptText.Text = rstCurrentTicket!Department
Me.DescriptionText = rstCurrentTicket!Description
Me.UrgencyText = rstCurrentTicket!Urgency
when I run this code i recieve an error code saying:
"Run-Time error: '3021'"
"no current record"
and it highlights this line of code:
NameText.Text = rstCurrentTicket!SubmiterName
any suggestions of how to fix this?

Your recordset has no results. You can check for this as follows:
If Not rstCurrentTicket.EOF Then
NameText.Text = rstCurrentTicket!SubmiterName
DeptText.Text = rstCurrentTicket!Department
Me.DescriptionText = rstCurrentTicket!Description
Me.UrgencyText = rstCurrentTicket!Urgency
End If
EOF = End Of File = the end of the recordset has been reached.

Keith is exactly right, but I wanted to give a little more detail
For ADO and DAO, you have a Begin-of-File marker (BOF)and an End-of-File marker(EOF). The records are returned like this
[BOF]
[Record one] <-
[Record two]
...
[Record n]
[EOF]
The arrow points to where the cursor is. The cursor points to which record in the record set that is returned.
When no records are returned, you get this
[BOF]
[EOF]
So, if both flags are set, there are no records. If EOF is set, either you have no records, or you've moved past the last record. (You move that cursor to the next record by this command.)
rstCurrentTicket.MoveNext
You can also check by
If (rstCurrentTicket.EOF and rstCurrentTicket.BOF) Then
msgbox "There were no Trouble Tickets found."
Else
'Do something here.
End If

Related

'Item' is not a member of 'DataRow()'

I am trying to use this code from this answer but I keep getting this error
'Item' is not a member of 'DataRow()'
Does anyone know why? Or how I can get the first row of a data table?
Dim results As DataRow() = Students.Select("ID=1 and FirstName='Karthik'", "ID")
Test1Highest.Text = results.Item("Name") & " Got the highest in test 1!"
From DataTable.Select Method, we can see that the results variable will be an Array of DataRow objects.
Therefore, to access the first item in the list, you will need to add an Array Indexer.
Change this line:
Test1Highest.Text = results.Item("Name") & " Got the highest in test 1!
to be
If results IsNot Nothing AndAlso results.Count > 0 Then
Test1Highest.Text = results(0).Item("Name") & " Got the highest in test 1!
Else
Test1Highest.Text = "No results!"
End If
Or, you can do (using FirstOrDefault())
Dim singleResult As DataRow = Students.Select("ID=1 and FirstName='Karthik'", "ID").FirstOrDefault()
If singleResult IsNot Nothing Then
Test1Highest.Text = singleResult.Item("Name") & " Got the highest in test 1!
Else
Test1Highest.Text = "No results!"
End If
Looking at the question you linked to, the accepted answer has the command FirstOrDefault() being called from the result of the Select statement. This, like the name suggests, will return the first item in the array or a Null value if there are no elements in the array.

recordset cannot find record

Hi all i have this situation in VB for Access.
GenraReport_Click() is the main function called when pressed a botton in the report.
Temp is a table containing some data like this:
Now i created a recordset rs to loop each record of Temp , by the field Item.
And it works , the problem is when i call the function prices that has to do exactley the same thing but on the field price.
The problem comes when i try to call rs!price (or rs![price] i tried both), it tells me that there are no records. I put a movefirst call at the end of the first loop to start again with the new function.
(i tried to do the main loop with price instead of item and it works so it's not the table and not the syntax the problem. What can it be?
Your Do Until loop is likely exceeding the number of records available in recordset, so compiler errors out at 'No Current Record'. Usually, the proper way to loop through a recordset is to set the iteration limit to the Recordset EOF property:
Dim rs As Recordset
Dim s As String, i As Integer
Set rs = CurrentDb.OpenRecordset("temp")
rs.MoveLast
rs.MoveFirst
s = "": i = 1
If rs.RecordCount > 0 Then
Do While Not rs.EOF ' OR Do Until rs.EOF
Select Case i
Case 1
s = CStr(rs!Price)
Case Is < rs.RecordCount
s = s & ", " & CStr(rs!Price)
Case Else
s = s & ", and " & CStr(rs!Price)
End Select
i = i + 1
rs.MoveNext
Loop
End if
rs.close
Set rs = Nothing

Getting error Multiple-step operation generated error

I am debugging some old code and I am getting error on this part
rs("country code").value = NullIfBlank(Request.Form("country code"))
The error says "Multiple-step operation generated errors. Check each status value."
I tried to understand what NullIfBlank means and to my understanding, I tried to rewrite the code this way:
If rs("country code").value Is Nothing Then
rs("country code").value = Request.Form("country code")
End If
now I am not getting an error when there is a value in rs("country code").value, but I get an error in this statement
rs("country code").value = Request.Form("country code")
My whole code looks like this
if request.form("submit")="Save Changes " or request.form("submit")="Save Changes to a New " then%>
<%
id = request.form("id")
if id is nothing then id = ""
cmd1.ActiveConnection = strconn
cmd1.CommandText = "FormBlankSpecial"
cmd1.CommandType = adCmdStoredProc
cmd1.Parameters.Append (cmd.CreateParameter("#id", adVarChar, adParamInput, 50, id))
rs.CursorLocation = adUseClient
rs.LockType = adLockPessimistic
rs.open (cmd1)
if cmd1.Parameters.count > 0 then
cmd1.Parameters.delete("#id")
end if
if request.form("submit")="Save Changes to a New" then
rs.addnew
rsmax.open ("FormBlankMax", strconn, adOpenKeyset, adLockPessimistic, adCmdStoredProc)
rs("idx").value=(1*zeroif(rsmax("maxid").value))+1
end if
' rs("country code").value = NullIfBlank(Request.Form("country code"))
' I keep getting error here
If rs("country code").value Is Nothing Then
rs("country code").value = Request.Form("country code")
End If
Below is the isnull function
Public Shared Function NullIfBlank(ByVal Str)
On Error Resume Next
NullIfBlank = ""
If Str = "" Then NullIfBlank = DBNull.Value Else NullIfBlank = Str
Return NullIfBlank
End Function
and the sql stored procedure looks like this
select isnull([Country Code], '') as [Country Code]
from testTable
when I do like this in sql statement
select [Country Code] as [Country Code]
from testTable
then I don't get that error.
any help will be greatly appreciated.
You have to understand:
Nothing is a special object that indicates that a variable that should contain an object does not. While that seems similar to n/Null pointers/references in other languages, you should not think "Null" when stumbling upon "Nothing".
Assigning an object (even this Nothing) to a variable needs Set in VBScript.
Null in VBScript is a special value that indicates that a variable that should contain a value does not. This is like Null in SQL.
(There is another special value to indicate not quite decent variable content in VBScript: Empty - it differs from Null in operations/comparisons.)
Assigning a value to a variable is done without Set in VBScript.
Vour:
id = request.form("id")
if id is nothing then id = ""
seems to read a string value from a form element into id. Then id is not an object and can not be compared to the Nothing object. Or you want to access the element/object - then you must use
Set id = request.form("id")
Your
If rs("country code").value Is Nothing Then
tries to check a database column value (probably a string) to the Nothing object. Depending on your column definition the field may contain Null - then you must check for Null (not Nothing):
If IsNull( rs("country code").value) Then
You should publish the NullIfBlank() function, because "Multiple Step" errors often point to SQL problems.

SSIS Script Task Debugging When Checking Value Comparison

I have this code in a script task:
Public Sub Main()
'
' Add your code here
'
Dim MonthFromSQL As String
Dim lastMonth As New Date(DateTime.Today.Year, DateTime.Today.Month - 1, 1)
Dim rcnt As Integer
Dim msg As String
'MsgBox("Month name from SQL is " & CStr(Dts.Variables("MonthNameFromSQL").Value))
rcnt = CInt(Dts.Variables("RowCount").Value)
If rcnt = 0 Then
msg = "Job returned 0 rows for month " & CStr(MonthName(lastMonth.Month, False)) & " - check with database operator that previous month's data has been loaded into the database."
Else
msg = "Job returned " & rcnt & " rows - Job Finished"
End If
'Pass message variable value out to be used in message
Dts.Variables("EmailMessage").Value = msg
Dts.TaskResult = Dts.Results.Success
End Sub
If I modify the IF statement to below to be able to check the month value from SQL DB against system month value it gives me a DTS script error saying that:
The type of the value being assigned to variable "User::EmailMessage" differs from the current variable type. Variables may not change type during execution. Variable types are strict, except for variables of type Object.
'First check month name from sql match system last month name
If CStr(MonthName(lastMonth.Month, False)) = CStr(Dts.Variables("MonthNameFromSQL").Value) Then
MsgBox("Month name variable equals last month value")
If rcnt = 0 Then
msg = "Job returned 0 rows for month " & CStr(MonthName(lastMonth.Month, False)) & " - check with outpatient database operator that previous month's data has been loaded into the database."
Else
msg = "Job returned " & rcnt & " rows - Job Finished"
End If
Else
'Put in code to handle if month values do not match
End If
I replaced:
If CStr(MonthName(lastMonth.Month, False)) = CStr(Dts.Variables("MonthNameFromSQL").Value) Then
MsgBox("Month name variable equals last month value")
With:
If 1=1 Then
MsgBox("Month name variable equals last month value")
Just to check it would work with a simple comparing statement and that it was something to do with the code I had in the IF statement, as I did not suspect it was anything to do with the msg variable I was populating, even though this was the error message.
So I realise it is something to do with:
If CStr(MonthName(lastMonth.Month, False)) = CStr(Dts.Variables("MonthNameFromSQL").Value) Then
The montNameFromSQL is populated with the result set of a previous SQL task, and then in this script I am using it to check against the system month name. I want to check these values and if a match then success and move onto to check the rows returned, and populate the message to send in my email task.
Hopefully it's something simple and a fresh pair of eyes can spot!
Thanks
Andrew
Either you have the wrong data types assigned (which is what the error message is stating) or you have not faithfully reproduced your code.
I created a package with 3 variables.
EmailMessage: String -
MonthNameFromSQL: String - July
RowCount: Int32 - 0
I configured my "SCR Works fine" task to allow read access to the second two variables and read/write access to EmailMessage.
Inside the script, I used your code. I ran it with your original that works and the one that doesn't work for you.
Public Sub Main()
Dim MonthFromSQL As String
Dim lastMonth As New Date(DateTime.Today.Year, DateTime.Today.Month - 1, 1)
Dim rcnt As Integer
Dim msg As String
'MsgBox("Month name from SQL is " & CStr(Dts.Variables("MonthNameFromSQL").Value))
rcnt = CInt(Dts.Variables("RowCount").Value)
'If rcnt = 0 Then
' msg = "Job returned 0 rows for month " & CStr(MonthName(lastMonth.Month, False)) & " - check with database operator that previous month's data has been loaded into the database."
'Else
' msg = "Job returned " & rcnt & " rows - Job Finished"
'End If
'First check month name from sql match system last month name
If CStr(MonthName(lastMonth.Month, False)) = CStr(Dts.Variables("MonthNameFromSQL").Value) Then
MsgBox("Month name variable equals last month value")
If rcnt = 0 Then
msg = "Job returned 0 rows for month " & CStr(MonthName(lastMonth.Month, False)) & " - check with outpatient database operator that previous month's data has been loaded into the database."
Else
msg = "Job returned " & rcnt & " rows - Job Finished"
End If
Else
'Put in code to handle if month values do not match
msg = "I am here"
End If
'Pass message variable value out to be used in message
Dts.Variables("EmailMessage").Value = msg
Dts.TaskResult = ScriptResults.Success
End Sub
As you can see from the value of the EmailMessage variable, it's populated and the script has completed.
This package is using SQL Server 2012 but the fundamentals of what you are trying has been available since 2005.
Integration Services (SSIS) Variables
Using Variables in the Script Task
only issue I see is with the data type of MonthNameFromSQL variable, somehow MonthNameFromSQL is assigned wrong data type or its getting null value.
I will recommend you to do the following.
Ensure that date_column datetime field in your table is NOT NULLABLE or Do null check in your sql statement to ensure that it is not passing any null values to the MonthNameFromSQL variable.
select distinct ISNULL(convert(varchar(12),(datename(month, date_column))), '') as monthName FROM dbo.table1
Delete the MonthNameFromSQL varialble from variablbe window(shown on
the left pane in visual studio), recreate this variable again
ensuring that scope of the variable is at package level and data
type is string type. select this variable from result set of execute
sql task properties.
If above step fails, recreate package freshly.

Check if email exists

I have a classic ASP page with some code to check if an email exists in the table as follows;
<%
'' //Check the submitted email against existing ones in the database
set CmdCheckEmail = server.CreateObject("ADODB.Command")
CmdCheckEmail.ActiveConnection = MM_dbconn_STRING
CmdCheckEmail.CommandText = "SELECT COUNT(ReferredEmail) AS 'CountEmail' FROM TenantReferral WHERE ReferredEmail = '" & Request("Email") & "'"
Response.Write(CmdCheckEmail.CommandText)
CmdCheckEmail.CommandType = 1
CmdCheckEmail.CommandTimeout = 0
CmdCheckEmail.Prepared = true
CmdCheckEmail.Execute()
countEmail = CmdCheckEmail("CountEmail")
set CmdCheckEmail = nothing
conn.close
set conn = nothing
If(countEmail >= 1) Then
Message = Message & "<p>This email address has already been referred.</p>"
End If
%>
However, the page is reporting the following error;
SELECT COUNT(ReferredEmail) AS 'CountEmail' FROM TenantReferral WHERE ReferredEmail = 'test#xyz.com'
ADODB.Command error '800a0cc1'
Item cannot be found in the collection corresponding to the requested name or ordinal.
/default2.asp, line 19
Line 19 is as follows;
countEmail = CmdCheckEmail("CountEmail")
The email does exist in the table and the table simply has the following columns; ReferredEmail and ReferredCode
I wondered if anyone might be able to shed any light on this error?
Thank you.
Note sure what database you are using but try changing your sql to:
SELECT COUNT(ReferredEmail) AS CountEmail FROM TenantReferral WHERE ReferredEmail = 'test#xyz.com'
Then change
CmdCheckEmail.Execute()
countEmail = CmdCheckEmail("CountEmail")
to
set rs = CmdCheckEmail.Execute()
countEmail = rs("CountEmail")
Also, you have a SQL injection issue with that query. You should be using parameterized queries.
CmdCheckEmail("CountEmail") tries to access the default member of the Command object, which is the parameters collection. However, you don't want to access a parameter but a field of the resulting recordset.
Try this (not tested):
Set rs=CmdCheckEmail.Execute()
countEmail = rs("CountEmail")
Apart from that, beware: This line:
CmdCheckEmail.CommandText = "SELECT COUNT(ReferredEmail) AS 'CountEmail' FROM TenantReferral WHERE ReferredEmail = '" & Request("Email") & "'"
is vulnerable to an SQL injection attack.
Never embed literal strings into SQL statement; use parameters instead. (In this case, you would do that using the Command.Parameters collection.)