I've got a SQL query in my VB6 project that is performing a three-way INNER JOIN in an Ms-Access database.
The VB6 query is:
SQL = "SELECT popsLines.stockCode, popsLines.orderNumber, popsOrders.dateOrdered, popsReceipts.dateReceived, popsReceipts.reference" & _
" FROM (popsOrders INNER JOIN popsLines ON popsOrders.orderNumber = popsLines.orderNumber)" & _
" INNER JOIN popsReceipts ON popsOrders.orderNumber = popsReceipts.orderNumber" & _
" WHERE (([WHERE popsLines].[stockCode]=" & sqlString(m_sStockCode) & "));"
This wasn't working, it returned an error saying
No value given for one or more required parameters
So then next thing I did was copy the value in the SQL variable and paste it into an Access query, with the value of the m_sStockCode parameter.
SELECT popsLines.stockCode, popsLines.orderNumber, popsOrders.dateOrdered, popsReceipts.dateReceived, popsReceipts.reference
FROM (popsOrders INNER JOIN popsLines ON popsOrders.orderNumber = popsLines.orderNumber)
INNER JOIN popsReceipts ON popsOrders.orderNumber = popsReceipts.orderNumber WHERE (([WHERE popsLines].[stockCode]="010010003"));
When executing this, it said
Enter Parameter Value: WHERE popsLines.StockCode
Why isn't it accepting the query as it is?
I've also tried changing there WHEREclause to
(( WHERE [popsLines].[stockCode]="010010003"));
but got
Syntax error (missing operator) in query expression '((WHERE [popsLines].[stockCode]="010010003"))'
The last part - your WHERE clause - is garbled. It should read:
.. WHERE ([popsLines].[stockCode]='010010003');
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 am trying to insert mulivalues of swab locations into a table that has the same tracking number. Here is the example:
tblMainSwapLocation (Table where i get my information form)
Asset_ID MAterial Swap_Location
MFG111 Brick Top left
MFG111 Plastic Top right
MFG113 Wood Center
tblCVLocation (Table where i want to insert information into)
TrackingID Asset_ID Swap_Location
99801 MFG111 Top left
99801 MFG111 Top right
I am using the following sql query to do the job, but i am having troubles with how the query should be.
strSQL = "Insert Into tblCVProject " & vbCrLf
strSQL = strSQL & "Values ( [pTrackNum], (SELECT MEQ.Asset_ID ,MEQ.SwabLocation" & vbCrLf
strSQL = strSQL & "FROM tblMainSwapLocation as MEQ " & vbCrLf
strSQL = strSQL & "WHERE MEQ.Asset_ID = [pAsset_ID] ))"
Debug.Print strSQL
Set qdf = dbs.CreateQueryDef(vbNullString, strSQL)
qdf.Parameters("pAssetID").Value = Me.cboAsset_Id
qdf.Parameters("pTrackNum").Value = TrackNum
The query in simplier form, It runs when the user clicks the save button.
Insert Into tblCVProject
Values ( [pTrackNum], (SELECT MEQ.Asset_ID ,MEQ.SwabLocation, MEQ.Equipment_Name
FROM tblMainSwapLocation as MEQ
WHERE MEQ.Asset_ID = [pAsset_ID] ))
This is the error I am getting:
The syntax of the INSERT statement is well explained at:
https://msdn.microsoft.com/en-us/library/bb208861(v=office.12).aspx
Either use VALUES (for single-record append query) or SELECT for multi-record append query.
Not enough info to give a clear answer.
I have guessed that your TrackingID column is defined as auto-number because I see nowhere a source for it
If you want to generate a record in tblCVLocation for each tblMainSwapLocation then you just have to do this :
INSERT INTO tblCVProject ([Asset_ID],[Swap_Location])
SELECT Asset_ID, Swap_Location FROM tblMainSwapLocation
If you want to insert only for some Asset_ID or material, then add a WHERE clause after the SELECT
If you want only the distinct pairs of Asset_ID + Swap_location then add a DISTINCT clause in the SELECT
I really can be more accurate with the information specified
I'm trying to call a procedure in a module that needs some arguments, thus:
MySQL code to be executed (extracted from the module's procedure):
Sub InsertRecord(ByVal tbl As String, ByVal cols() As String, ByVal params() As String, ByVal colCondition As String, ByVal paramCondition As String) 'As String
:
:
comA.CommandText = "INSERT INTO " & tbl & " (" & newCols & ") SELECT * FROM (SELECT #params) AS tmp "
comA.CommandText &= "WHERE NOT EXISTS (SELECT " & newCols & " FROM " & tbl & " WHERE " & colCondition & " = #param) limit 1"
comA.Parameters.AddWithValue("#param", paramCondition)
comA.Parameters.AddWithValue("#params", newParams)
:
:
End Sub
Call Code:
myModule.SaveInfo("myprod", {"col_a", "col_b", "col_c", "col_d", "col_e", "col_f", "col_g", "col_h"}, _
{val_a, val_b, val_c, val_d, val_e, val_f, val_g, val_h}, "col_b", val_b)
hint: newCols and newParams (obtained from cols() and params() respectively) are comma-delineated lists of columns of the table in question and values to be inserted respectively.
When i run my code, i get the error: column count doesn't match value count at row 1
Please how do i address this issue? I've been on it for some days now.
Thanks in advance.
Edit:
I decided to write the code on the sub, instead of using a module. Here is the full subroutine:
Private Sub SaveProduct(ByVal p_code As String, ByVal b_id As String, ByVal m_id As String, _
ByVal c_id As String, ByVal des As String, ByVal o_det As String)
'modNewData.InsertRecord("products", {"prd_code", "brnd_id", "mnu_id", "cat_id", "prd_description", "prd_details", "prd_create_date", "prd_last_update"}, _
' {p_code, b_id, m_id, c_id, des, o_det, Date.Now.ToShortDateString, Date.Now.ToShortDateString}, "brnd_id", b_id)
con = New MySqlConnection("Server=localhost; Database=inventory_db; Uid=root; Pwd=;")
comA = New MySqlCommand
'INSERT NEW RECORD.
comA.CommandText = "INSERT INTO products (prd_code, brnd_id, mnu_id, cat_id, prd_description, prd_details, prd_create_date, prd_last_update) "
comA.CommandText &= "SELECT * FROM (SELECT #params) AS tmp "
comA.CommandText &= "WHERE NOT EXISTS (SELECT prd_code, brnd_id, mnu_id, cat_id, prd_description, prd_details, prd_create_date, prd_last_update FROM products "
comA.CommandText &= "WHERE brnd_id = #param) limit 1"
comA.Parameters.AddWithValue("#param", b_id)
comA.Parameters.AddWithValue("#params", {p_code, b_id, m_id, c_id, des, o_det, Date.Now.ToShortDateString, Date.Now.ToShortDateString})
comA.Connection = con
con.Open()
comA.ExecuteNonQuery()
con.Close()
'Release used up components
comA.Parameters.Clear()
comA.Dispose()
comA = Nothing
con = Nothing
MsgBox("done.")
At this point, i don't seem to know what i'm doing, but I know what i want to achieve - insert a new record in a table. I strongly believe that there's a problem with my sql code, but can't figure out exactly what it is. Your help is highly needed at this point. Thanks in advance.
EDIT 2:
I tweaked the mysql insert code above, and now i can successfully insert new record to my table. But one more problem exists: I get this <Unable to read data> error in my datetime and timestamp columns respectively.
id prd_code brnd_id mnu_id cat_id desc details create_date (datetime) last_update(timestamp)
10 PM-16326 10 9 6 Red NULL 10/15/2013 8:22:00 AM 7/16/2015 9:13:03 AM
17 PM-55326 23 28 11 Olive oil n/a <Unable to read data> <Unable to read data>
Here's the new insert code:
'INSERT NEW RECORD.
comA.CommandText = "INSERT INTO products (prd_code, brnd_id, mnu_id, cat_id, prd_description, prd_details, prd_create_date, prd_last_update) "
comA.CommandText &= "SELECT * FROM (SELECT #p_code, #b_id, #m_id, #c_id, #des, #o_det, '11/11/2015 9:00:00 AM', '11/12/2015 9:00:00 AM') AS tmp "
comA.CommandText &= "WHERE NOT EXISTS (SELECT prd_code, brnd_id, mnu_id, cat_id, prd_description, prd_details, prd_create_date, prd_last_update FROM products "
comA.CommandText &= "WHERE brnd_id = #b_id) limit 1"
comA.Parameters.AddWithValue("#p_code", p_code)
comA.Parameters.AddWithValue("#b_id", b_id)
comA.Parameters.AddWithValue("#m_id", m_id)
comA.Parameters.AddWithValue("#c_id", c_id)
comA.Parameters.AddWithValue("#des", des)
comA.Parameters.AddWithValue("#o_det", o_det)
If i replaced the two dates above with date.now.tostring, I'll get the error: you have repeated columns...
I really need your help guys. Thanks in advance.
The columns you pass to the procedure (which do match) are called cols, but in the query you use newCols.
The MySQL error you get means that the values you insert are not in the same number as the columns you say they should fill: you cannot insert four values into five columns, or three.
So what is happening is clearly that you do something to retrieve newCols from cols, in the part of code you have omitted. Probably, depending on some condition, you add some columns (or leave some out). That is what is causing your trouble. You should modify at the same time, apparently, the value of params into some other value, possibly newParams.
Also, perhaps the condition is not always true, and you observe the function misbehaving only occasionally, or passing some test (because that test does not trigger the column-modifying bug).
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 & "')"