I would like to save the result from the SELECT to a variable, in MS Access.
It should select the most recent offer price from the PriceFeed table where stock symbol in the table matches the selected item from the form comboBox.
Dim sq2 As Variant
sql = "SELECT PriceFeed.Offer FROM PriceFeed WHERE PriceFeed.StockSymbol = Me.CBSymbol.Column(1) AND DateTime =(SELECT MAX([PriceFeed.DateTime])FROM PriceFeed)"
DoCmd.RunSQL sq2
You can use DMax and DLookup:
RecentPrice = DLookup("Offer", "PriceFeed", "StockSymbol = " & Me.CBSymbol.Column(1) & " AND DateTime = DMax('DateTime', 'PriceFeed')")
To avoid errors if no CBSymbol has been selected:
RecentPrice = DLookup("Offer", "PriceFeed", "StockSymbol = " & Nz(Me.CBSymbol.Column(1), 0) & " AND DateTime = DMax('DateTime', 'PriceFeed')")
Related
I need to make a query in a MySQL database returning records with the current date.
I found the command below and it works perfectly inside MySQL:
SELECT * FROM TBAvaliacoes WHERE DataHora = (Date_Format(Now(),'%Y-%m-%d'))
But when I do this inside ASP, it returns me the error below:
See how I am doing:
' ## LISTA RAMAIS
Set cmdListaAvaliacoes = Server.CreateObject("ADODB.Command")
cmdListaAvaliacoes.ActiveConnection = conn
cmdListaAvaliacoes.CommandText = "SELECT * FROM TBAvaliacoes WHERE DataHora = (Date_Format("&Now()&",'%Y-%m-%d'))"
response.write cmdListaAvaliacoes.CommandText
cmdListaAvaliacoes.CommandType = 1
Set rsListaAvaliacoes = Server.CreateObject("ADODB.Recordset")
rsListaAvaliacoes.Open cmdListaAvaliacoes, , 3, 3
If I enclose Now () in single quotation marks, it gives no error, but returns nothing.
Does anyone know how to get around this?
Awaiting,
If you want to call the Now() function defined by MySql then you shouldn't use the VB.NET function and concatenate its output to your sql. Just write the code exactly how you write it in the MySql Workbench
cmdListaAvaliacoes.CommandText = "SELECT * FROM TBAvaliacoes
WHERE DataHora = (Date_Format(Now(),'%Y-%m-%d'))"
If you want to pass a particular date then you need to format your date as expected by MySql
Dim myDate As DateTime = new DateTime(2019,8,10)
cmdListaAvaliacoes.CommandText = "SELECT * FROM TBAvaliacoes
WHERE DataHora = '" & myDate.ToString("yyyy-MM-dd") & "'"
But in this case the better approach is to use parameters (even if you have full control of what your date is)
Dim myDate As DateTime = new DateTime(2019,8,10)
cmdListaAvaliacoes.CommandText = "SELECT * FROM TBAvaliacoes
WHERE DataHora = #dat"
Dim prm = cmdListaAvaliacoes.CreateParameter("#dat", adDBDate, adParamInput)
prm.Value = myDate
cmdListaAvaliacoes.parameters.Append prm
Side note
A lot of time has passed from the last time I have used ADODB. So the parameter solution is how I remember it. Search on the net for more complete CreateParameter examples
I am trying to get an Access SQL query that does this (semi-pseudocode below)
UPDATE SignIn SET SignIn.Complete=True, CompletedBy=(Select [FirstName] & " " & [LastName] AS EmployeeName From UserList where POid = Forms!HiddenUserCheck!txtPOid), CompletedDateTime=Now()
So after the query would run, the data in the database would look like
Complete EmployeeName CompletedDateTime
True John Smith 3/23/2017 8:34:10 AM
THe update query doesn't work because of syntax and not sure how to fix it.
The exact error message is
Invalid Memo, OLE, or HyperLink Object in subquery '[FirstName] & " "
& [LastName]'.
The query could be throwing a fit because of the Double Exclamation marks. Instead of
Forms!HiddenUserCheck!txtPOid
Try
Forms!HiddenUserCheck.txtPOid
You also have an extra ) at the end of your WHERE Statment
OK, then your issue may be that the subquery may return more than one record:
UPDATE
SignIn
SET
SignIn.Complete=True,
CompletedBy =
(Select First([FirstName] & " " & [LastName]) AS EmployeeName
From UserList
Where POid = Forms!HiddenUserCheck!txtPOid),
CompletedDateTime = Now()
If your name fields are Memo/LongText fields, that may be the source of the error. If so, try:
UPDATE
SignIn
SET
SignIn.Complete=True,
CompletedBy =
(Select First(Left([FirstName], 255) & " " & Left([LastName], 255)) AS EmployeeName
From UserList
Where POid = Forms!HiddenUserCheck!txtPOid),
CompletedDateTime = Now()
Edit.
You may try using DLookup for the subquery:
UPDATE
SignIn
SET
SignIn.Complete=True,
CompletedBy =
DLookup("[FirstName] & " " & [LastName]", "UserList", "POid = " & Forms!HiddenUserCheck!txtPOid & ""),
CompletedDateTime = Now()
I have a vb.net program that queries a mysql database. i can search and get records between to dates with this code:
sqlQRY12 = "SELECT * from mating WHERE date BETWEEN '" & export_daily_date_DateTimePicker1.Text & "' AND '" & export_daily_date_DateTimePicker2.Text & "' AND chkbox = '0' ORDER BY lot_id ASC"
my format for my date is:
export_daily_date_DateTimePicker1.Format = DateTimePickerFormat.Custom
export_daily_date_DateTimePicker1.CustomFormat = "MM/dd/yy"
export_daily_date_DateTimePicker2.Format = DateTimePickerFormat.Custom
export_daily_date_DateTimePicker2.CustomFormat = "MM/dd/yy"
however if i try to search between two years like 12/20/13 - 02/20/14 I return no records when i know they exist? Any help would be great ty
Generally dates expressed as strings in database queries should be in the format "YYYY-MM-DD".
You essentially want your executed query to be this:
SELECT * from mating
WHERE date BETWEEN '2013-12-20' AND '2014-02-20'
So change the format of your dtpickers to be yyyy-mm-dd like this:
export_daily_date_DateTimePicker1.Format = DateTimePickerFormat.Custom
export_daily_date_DateTimePicker1.CustomFormat = "yyyy-MM-dd"
export_daily_date_DateTimePicker2.Format = DateTimePickerFormat.Custom
export_daily_date_DateTimePicker2.CustomFormat = "yyyy-MM-dd"
You should never concatenate values into your SQL commands. If at all possible, you should use parameters. With parameters, you can specify the value as it's actual type (Date) rather than as the string representation. The ADO Provider will handle converting the value correctly for you.
cmd.CommandText = "SELECT * from mating WHERE date BETWEEN #date1 AND #date2 AND chkbox = '0' ORDER BY lot_id ASC"
cmd.Parameters.AddWithValue("#date1", export_daily_date_DateTimePicker2.Value)
cmd.Parameters.AddWithValue("#date2", export_daily_date_DateTimePicker2.Value)
I have been racking my brain over this all day today.
I have the following ASP code that uses a Request.Querystring input from a dropdown box
to launch a select statement. The querystrinch does show in the ?= URL but will only work on
columns in the Microsoft SQL DB that are numeric. I cant lookup names or simple 3 character fields.
CODE:
If Request.QueryString("m") > 0 Then
filterID = Request.QueryString("m")
filterColmn = "imDegree"
Else filterID = 0
End If
If filterID > 0 Then
SQlQuery = "SELECT * FROM v_InternImport WHERE iID IN (SELECT iID FROM v_InternImport WHERE " & filterColmn & " = " & filterID & ")"
End If
End If
I understand that this select statement as a sub select stament in it but I cant even get a staight reuturn from my DB. The select statement references the same view that populates the main asp page that loads before and the shows fine?
When you pass a string to SQL Server, you need to surround it with single quotes.
When you pass a number, you don't use the quotes.
So, when you say (summarizing)
SELECT * FROM table WHERE filterColumn = filterID
you should be sending a number.
To match a string:
SELECT * FROM table WHERE filterColumn = 'filterID'
This assumes that you have solved any other problems mentioned by the commenters about whether you even have a value in the filterID variable. I heartly concur with the recommendation to use parameterized queries.
Edit: The single quotes go inside the double quotes.
SQlQuery = "SELECT * FROM v_InternImport
WHERE iID IN (SELECT iID FROM v_InternImport
WHERE " & filterColmn & " = '" & filterID & "')"
I have a query to return random distinct rows from an Access database. Here is the query:
SELECT * FROM
(SELECT DISTINCT m.MemberID, m.Title, m.FullName, m.Address,
m.Phone, m.EmailAddress, m.WebsiteAddress FROM Members AS m INNER JOIN MembersForType AS t ON m.MemberID = t.MemberID WHERE
(Category = 'MemberType1' OR Category = 'MemberType2')) as Members
ORDER BY RND(members.MemberID) DESC
When I run this in Access it returns the rows in different order every time, as per the random sort order. When I run it through my web app however the rows return in the same order every time. Here is how I call it in my code-behind:
private void BindData()
{
using (AccessDataSource ds = new AccessDataSource("~/App_Data/mydb.mdb", GetSQLStatement()))
{
ds.DataSourceMode = SqlDataSourceMode.DataReader;
ds.CacheDuration = 0;
ds.CacheExpirationPolicy = DataSourceCacheExpiry.Absolute;
ds.EnableCaching = false;
listing.DataSource = ds.Select(new DataSourceSelectArguments());
listing.DataBind();
if (listing.Items.Count == 0)
noResults.Visible = true;
else
noResults.Visible = false;
}
}
I added in all that stuff about caching because I thought maybe the query was being cached but the result was the same. I put a breakpoint in the code to make sure the query was the same as above and it was.
Any ideas? This is driving me nuts.
When executing the ACE/Jet RND function against a new connection the same seed value is used each time. When using MS Access you are using the same connection each time, which explains why you get a different value each time.
Consider these VBA examples: the first uses a new connection on each iteration:
Sub TestDiff()
Dim con As Object
Set con = CreateObject("ADODB.Connection")
With con
.ConnectionString = _
"Provider=MSDataShape;Data " & _
"Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\Tempo\Test_Access2007.accdb"
.CursorLocation = 3
Dim i As Long
For i = 0 To 2
.Open
Debug.Print .Execute("SELECT RND FROM OneRowTable;")(0)
.Close
Next
End With
End Sub
Output:
0.705547511577606
0.705547511577606
0.705547511577606
Note the same value each time.
The second example uses the same connection on each iteration (the .Open and .Close statements are relocated outside the loop):
Sub TestSame()
Dim con As Object
Set con = CreateObject("ADODB.Connection")
With con
.ConnectionString = _
"Provider=MSDataShape;Data " & _
"Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\Tempo\Test_Access2007.accdb"
.CursorLocation = 3
.Open
Dim i As Long
For i = 0 To 2
Debug.Print .Execute("SELECT RND FROM OneRowTable;")(0)
Next
.Close
End With
End Sub
Output:
0.705547511577606
0.533424019813538
0.579518616199493
Note different values each time.
In VBA code you can use the Randomize keyword to seed the Rnd() function but I don't think this can be done in ACE/Jet. One workaround is to use the least significant decimal portion of the ACE/Jet the NOW() niladic function e.g. something like:
SELECT CDBL(NOW()) - ROUND(CDBL(NOW()), 4) FROM OneRowTable
I would move the RND into the inner SELECT
SELECT * FROM
(SELECT DISTINCT m.MemberID, RND(m.MemberID) as SortOrder, m.Title,
m.FullName, m.Address, m.Phone, m.EmailAddress, m.WebsiteAddress
FROM Members AS m
INNER JOIN MembersForType AS t ON m.MemberID = t.MemberID
WHERE
(Category = 'MemberType1' OR Category = 'MemberType2')) as Members
ORDER BY
Members.SortOrder DESC
You can use time as one argument to the RND field
Dim Now As DateTime = DateTime.Now
Dim millSec As Integer = Now.Millisecond
finalQuery = "SELECT * FROM wordInfo ORDER BY Rnd(-(1000* ROUND(" + millSec.ToString("N") + ", 0)) * [ID])"
So here from date and time value, millisecond value is taken which will be integer and it is used in sql query by rounding it.
wordInfo is table name
ID is the column name in database table
This gives random order every time (since millisecond value is different) be it same connection or new connection.