I would like to know how I could assign the result of an SQL query to a variable.
I have the query below :
set userid = Server.CreateObject("adodb.recordset")
user = "SELECT id FROM Users WHERE UserEmail = '" & UserEmail & "'"
userid.Open query,OLSLive,1,3
and I would like to assign the result of the query so that I can pass it as a parameter to a stored procedure.
Assuming one value is expected to be returned you simply need to read the recordsets 1st value;
userid.Open query,OLSLive,1,3
if not userid.eof then 'check for rows
your_variable = userid.collect(0) 'read 1st column, 1st row
...
else
'no matching row
I'm going to guess that this is VBScript...
userID.Open query,OSLive,1,3
if not userID.eof then
variableNamedSomething = recordset("id")
else
' something else
end if
'... get rid of the connection
userID.Close
set userID = nothing
OSLive.Close
set OSLive = nothing
Related
I have to run a SQL query and return a count and then pass that count back to a LotusScript function in order to place the value on a form.
The result from the SQL query
sqlStatement = select count(GMCPLN#A) as NumRecords from [database] where (GER#<=3 and GER#<=3) AND GTRMDT = 0
returns
How do I now access the value of NumRecords in the LotusScript code?
The following code is a quick cut and paste of an agent I have coded that retrieves SQL data. I've put your statement in and have set a print statement to show the result. Hope this helps.
Options
Uselsx "*LSXODBC"
Sub Initialize
Set con = New ODBCConnection()
Set qry = New ODBCQuery()
Set res = New ODBCResultSet()
con.SilentMode = True
If con.ConnectTo("DATABASE_NAME", "USER", "PASSWORD") Then
Set qry.Connection = con
Set res.Query = qry
qry.SQL = {select count(GMCPLN#A) as NumRecords from [database] where (GER#<=3 and GER#<=3) AND GTRMDT = 0}
If Not res.Execute Then
Messagebox res.GetExtendedErrorMessage,48,res.GetErrorMessage
Exit Sub
End If
Do
res.NextRow
Print "NumRecords = " + res.GetValue("NumRecords")
Loop Until res.IsEndOfData
res.Close(DB_CLOSE)
con.Disconnect
End Sub
I am looping through a listbox, and I need to get the same value you would get if you did .selectvalue, but without selecting the row. This is how I am doing it now, and it seems dumb.
For intCtr = 0 To lstUserRoleAll.Items.Count -1
lstUserRoleAll.SelectedIndex = intCtr
InsertUserRoles(lstUserRoleAll.SelectedValue)
Next
I have read that lstUserRoleAll.Items(intCtr).value should work, but value isn't a member of that. Also, lstUserRoleAll.Items(intCtr).tostring gets me the text "System.Data.DataRowView".
Surely there is a better way to do this.
Here is the code that I use to add the rows:
Dim rsSelectedGroups As DataTable
strSQL = "SELECT UID, Name "
[Rest of query]
rsSelectedGroups = DataAccess.GetDataTable(strSQL)
lstUserRoleCurrent.DataSource = rsSelectedGroups
lstUserRoleCurrent.ValueMember = "UID"
lstUserRoleCurrent.DisplayMember = "Name"
Because I populated the listbox with a datatable, the following code works. I did not realize that is what was being returned.
For intCtr = 0 To lstUserRoleAll.Items.Count
InsertUserRoles(lstUserRoleAll.Items(intCtr).Item("UID"))
Next
I really do not understand why the if test always fails. I have validated the session variable sCrs_cde (course code) is correct and exists in only one of the multiple records returned by the sql query. (It is part of a foreign key tied to year and semester). I am trying to sert the value for the course title, but it is always writing out as an empty value ('')
Dim Recordset1
Dim Recordset1_cmd
Dim Recordset1_numRows
Set Recordset1_cmd = Server.CreateObject ("ADODB.Command")
Recordset1_cmd.ActiveConnection = MM_Jenz_STRING
Recordset1_cmd.CommandText = "SELECT ID_NUM, Crs_Title, YR_CDE, TRM_CDE, CRS_CDE, TRANSACTION_STS, SUBTERM_CDE FROM dbo.STUDENT_CRS_HIST WHERE ID_NUM = ? And Transaction_sts = 'C' "
Recordset1_cmd.Prepared = true
Recordset1_cmd.Parameters.Append Recordset1_cmd.CreateParameter("param1", 5, 1, -1, Recordset1__MMColParam) ' adDouble
Set Recordset1 = Recordset1_cmd.Execute
Recordset1_numRows = 0
%>
<%
Do While not Recordset1.Eof
response.write(Recordset1.Fields.Item("CRS_cde").Value)
IF (Recordset1.Fields.Item("CRS_cde").Value) = (Session("sCrs_cde")) THEN
Session("sCrs_Title") = (Recordset1.Fields.Item("CRS_Title").Value)
Session("sYr_cde") = (Recordset1.Fields.Item("YR_CDE").Value)
Session("sTrm_cde") = (Recordset1.Fields.Item("Trm_Cde").Value)
Session("sSubterm_cde") = (Recordset1.Fields.Item("Subterm_cde").Value)
EXIT Do
ELSE
Recordset1.movenext
END IF
Loop
Thank you everyone. I made a boneheaded mistake every programming 101 class teaches. I did not rtrim the values. I don't know where the extra spaces came from since both values were retrieved from the database (different tables), but after rtrimming both values in the if statement, I finally got it to pass.
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
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.)