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.
Related
I am writing a method in VB.Net that runs a LINQ query on my database, and puts the information from the query into textboxes on a form.
Public Sub OpenPartWindow(ByVal partNumber As String)
Using dbContext As New DB_LINQDataContext
Dim query = (From p In dbContext.Parts
Join ppl In dbContext.Part_Price_Logs On p.Part_ID Equals ppl.Part_ID
Where p.Part_Number = partNumber
Select p.Part_Number, p.Part_Description, p.Part_Information, p.Supplier.Supplier_Name, _
p.Part_Manufacturer.Manufacturer_Name, p.Part_Subcategory.Part_Category.Category_Description, _
p.Part_Subcategory.Subcategory_Description, ppl.Cost_Per_Unit, ppl.Discount_Percentage).First()
MessageBox.Show(query.ToString())
txtPartNum.Text = query.Part_Number.ToString()
txtSupplier.Text = query.Supplier_Name.ToString()
txtManufacturer.Text = query.Manufacturer_Name.ToString()
txtPrice.Text = query.Cost_Per_Unit.ToString()
txtDiscount.Text = query.Discount_Percentage.ToString()
txtDescription.Text = query.Part_Description.ToString()
txtInfo.Text = query.Part_Information.ToString()
Me.Show()
End Using
End Sub
The issue I am having right now is with the last field, the txtInfo TextBox. You see the Part_Information field on the database allows NULL values. So when I go to fill the field when the field is null I am getting a NullReferenceException, which is understandable. However I cannot find a way to get around this exception.
I've tried:
If Not IsNothing(query._Part_Information.ToString()) Then
As well as
If query.Part_Information.Length > 0 Then
As If statements to run through first. But I keep getting the error each time. So I am confused on how I am suppose to deal with this error.
You can use either of the following options:
txtInfo.Text = String.Format("{0}", query.Part_Information)
txtInfo.Text = $"{query.Part_Information}" → $ - String Interpolation
txtInfo.Text = query.Part_Information?.ToString() → ?. - Null Conditional Operator
If query.Part_Information is null, the first two expressions result in Sting.Empty and the last one result in Nothing.
I have built a form with unbound fields designed so a user can input a date range, a facility name (these come from a combobox), and a badge number to generate a query in Access. I want to be able to return results within the selected date range for all facilities if the field is left blank or just the ones for a particular facility if one is selected. I also want to be able to limit the results to those that match an person's badge number.
So the possibilities I want would be:
Date Range = defined by user | Facility - All if not selected | Badge # = All if not selected
Date Range = defined by user | Facility - All if not selected | Badge # = defined by user
Date Range = defined by user | Facility - defined by user | Badge # = All if not selected
Date Range = defined by user | Facility - defined by user | Badge # = defined by user
I originally built it with just the date range and facility name and it worked fine. When I try to add in the Badge # it doesn't really work correctly.
My SQL for the WHERE TO section is:
WHERE (((Diversion.Transaction_Date) Between [Forms]![Parameters]![FromDate] And [Forms]![Parameters]![ToDate])
AND ((Diversion.Employee_Badge_Number)=[Forms]![Parameters]![BadgeNumber])
AND ((Diversion.Facility)=[Forms]![Parameters]![FacilitySelect]))
OR (((Diversion.Transaction_Date) Between [Forms]![Parameters]![FromDate] And [Forms]![Parameters]![ToDate])
AND ((Diversion.Facility)=[Forms]![Parameters]![FacilitySelect])
AND ((([Diversion].[Employee_Badge_Number]) Like [Forms]![Parameters]![BadgeNumber]) Is Null))
OR (((Diversion.Transaction_Date) Between [Forms]![Parameters]![FromDate] And [Forms]![Parameters]![ToDate])
AND ((Diversion.Employee_Badge_Number)=[Forms]![Parameters]![BadgeNumber])
AND ((([Diversion].[Facility]) Like [Forms]![Parameters]![FacilitySelect]) Is Null))
OR (((Diversion.Transaction_Date) Between [Forms]![Parameters]![FromDate] And [Forms]![Parameters]![ToDate])
AND ((([Diversion].[Employee_Badge_Number]) Like [Forms]![Parameters]![BadgeNumber]) Is Null)
AND ((([Diversion].[Facility]) Like [Forms]![Parameters]![FacilitySelect]) Is Null))
OR (((([Diversion].[Facility]) Like [Forms]![Parameters]![FacilitySelect]) Is Null));
To me, it looks like it is including the four possible results that I want to get from the form, but it isn't working right. For instance, if I leave the facility field blank, and define the badge number, it is still giving me all of the results. If I define the facility and define the badge number it does give me the correct results.
Any ideas?
This might give you some ideas building a dynamic query with multiple criteria values. In this example the user can pick any number of the criteria. It is written in VB.Net. It works with Access. I check each field to see if any criteria was provided then append it to the query if there is a valid value.
I used Interpolated strings just because it is easier to see where the spaces go. The alternative is:
String.Format("RoasterId = {0} ", itgRoaster)
I also used a String builder which is an efficient way to alter strings without the overhead of creating and disposing of them with each append. You could just use &= if this is not available in VBA.
Dim bolNeedAnd As Boolean = False
Dim sb As New Text.StringBuilder
sb.Append("SELECT Coffees.ID, Coffees.[Name], Coffees.RoasterID, Roasters.[Name], Coffees.[Type],Coffees.Rating, Coffees.Comment, Coffees.Description, Coffees.Roast, Coffees.IsExtraBold, Coffees.IsFavorite
From Coffees Inner Join Roasters on Coffees.RoasterID = Roasters.ID Where ")
If itgRoaster <> 0 Then
sb.Append($"RoasterID = {itgRoaster} ")
bolNeedAnd = True
End If
If strRoast <> "" Then
If bolNeedAnd Then
sb.Append($"AND Roast = '{strRoast}' ")
Else
sb.Append($"Roast = '{strRoast}' ")
End If
bolNeedAnd = True
End If
If strType <> "" Then
If bolNeedAnd Then
sb.Append($"AND Type = '{strType}' ")
Else
sb.Append($"Type = '{strType}' ")
End If
bolNeedAnd = True
End If
If strRating <> "" Then
If bolNeedAnd Then
sb.Append($"AND Rating = '{strRating}' ")
Else
sb.Append($"Rating = '{strRating}' ")
End If
bolNeedAnd = True
End If
If bolBold Then
If bolNeedAnd Then
sb.Append("AND IsExtraBold = 1 ")
Else
sb.Append("IsExtraBold = 1 ")
End If
bolNeedAnd = True
End If
If bolFavorite Then
If bolNeedAnd Then
sb.Append("AND IsFavorite = 1 ")
Else
sb.Append("IsFavorite = 1 ")
End If
End If
sb.Append("Order By Coffees.[Name];")
Debug.Print(sb.ToString)
Dim cmd As New OleDbCommand With {
.Connection = cn,
.CommandType = CommandType.Text,
.CommandText = sb.ToString}
I have a problem accessing a Stored Procedure via ASP from an SQL Database.
This is my code for the recordset:
Dim com_AntwoordenPerVraag__mem_id
com_AntwoordenPerVraag__mem_id = "0"
If Session("MM_MemberID") <> "" Then
com_AntwoordenPerVraag__mem_id = Session("MM_MemberID")
End If
Dim com_AntwoordenPerVraag__cat_id
com_AntwoordenPerVraag__cat_id = "0"
If Request.QueryString("cat_id") <> "" Then
com_AntwoordenPerVraag__cat_id = Request.QueryString("cat_id")
End If
set com_AntwoordenPerVraag = Server.CreateObject("ADODB.Command")
com_AntwoordenPerVraag.ActiveConnection = MM_modular_STRING
com_AntwoordenPerVraag.CommandText = "dbo.spAantal_antwoorden_per_vraag_per_member"
com_AntwoordenPerVraag.Parameters.Append com_AntwoordenPerVraag.CreateParameter("#RETURN_VALUE", 3, 4)
com_AntwoordenPerVraag.Parameters.Append com_AntwoordenPerVraag.CreateParameter("#mem_id", 3, 1,2,com_AntwoordenPerVraag__mem_id)
com_AntwoordenPerVraag.Parameters.Append com_AntwoordenPerVraag.CreateParameter("#cat_id", 3, 1,2,com_AntwoordenPerVraag__cat_id)
com_AntwoordenPerVraag.CommandType = 4
com_AntwoordenPerVraag.CommandTimeout = 0
com_AntwoordenPerVraag.Prepared = true
set rs_AntwoordenPerVraag = com_AntwoordenPerVraag.Execute
rs_AntwoordenPerVraag_numRows = 0
I get the following error message:
ADODB.Recordset error '800a0e78'
Operation is not allowed when the object is closed.
I get the message here:
If rs_AntwoordenPerVraag.EOF And rs_AntwoordenPerVraag.BOF Then
EDIT
I found the solution.
After:
set rs_AntwoordenPerVraag = com_AntwoordenPerVraag.Execute
I put:
If rs_AntwoordenPerVraag.State <> 1 Then
While rs_AntwoordenPerVraag.State <> 1
Set rs_AntwoordenPerVraag = rs_AntwoordenPerVraag.NextRecordset
Wend
End If
And now it works :-)
Your command needs a connection object, and it needs to be opened, rather than just a connection string.
See http://support.microsoft.com/kb/300382
Additionally, your code will be clearer if you import the ADODB constants file, and use those (ie: https://web.archive.org/web/20210513005432/https://www.4guysfromrolla.com/webtech/faq/Beginner/faq7.shtml )
The problem that you have calling the stored procedure is the number of lines touched by each query that is returned by SQL-Server inside a closed recordset before the final resultset. You can either look for the next recordset as you have already found or you can add the following instruction at the beginning of your SP in order to eliminate the sending of the number of lines for each query.
SET NOCOUNT ON
I prefer this last solution as it make the VBScript code simpler but it's just a matter of taste.
OP itself have found the solution and it works! Really Thanks to him.
After:
set rs_AntwoordenPerVraag = com_AntwoordenPerVraag.Execute
put:
If rs_AntwoordenPerVraag.State <> 1 Then
While rs_AntwoordenPerVraag.State <> 1
Set rs_AntwoordenPerVraag = rs_AntwoordenPerVraag.NextRecordset
Wend
End If
How would I structure a query for mongodB to make a 'stored procedure' or make the request to select an id which is marked active and then delete that field immediately or mark it as inactive; whichever one has the better performance. Here is the collection structure:
db = server.GetDatabase("test")
siteCollection = db("test")
collection = db.GetCollection(Of BsonDocument)("siteids")
Dim book As BsonDocument = New BsonDocument() _
.Add("siteid", BsonValue.Create(BsonType.String)) _
.Add("active", BsonValue.Create(BsonType.String))
collection.Insert(book)
I found the java version and not sure if this will work and what is .net syntax
db.things.find( { x : 4 } , { j : 1 } )
This apparantly finds records where x = 4 but only return where j = 1 so I want one siteid where active = 'N'
Thanks; here is what I have come up with thus far:
' Dim squery = Query.EQ("active", "Y")
Dim squery = Query.EQ("active", "Y")
Dim ssort = SortBy.Null
Dim uupdate = Update.[Set]("active", "N")
Dim result = collection.FindAndModify(squery, ssort, uupdate)
' Dim dresult = collection.FindAs(Of BsonDocument)(squery)
Dim newSiteId As String = dresult.Count
As you can see the first line commented out I thought a simple select would be implemented but that comes back null. Then with the second last statement commented out that too returned value Null.
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.)