SELECT INTO inserts only the last row - VBA, Access 2000? - vba

I have this SQL string which I create in a Loop:
"SELECT '" & Trim(Str(j)) & "' AS cpa, Count(Val('" & rsCPANezbirni("tipprod") & "')) AS BrojProd, Sum(Val('" & rsCPANezbirni("povrsina") & "')) AS p, Sum(Val('" & rsCPANezbirni("pmagacin") & "')) AS pm INTO T14_KPD_CPA_samo_podatoci FROM CPA_nezbirni WHERE (t4k" & Trim(Str(j)) & "<>'' Or t4k" & Trim(Str(j)) & " Is Not Null);"
And the loop I use is:
Dim j As Integer
j = 1
Do While j <= 3
cpaSelectSQL = "SELECT '" & Trim(Str(j)) & "' AS cpa, Count(Val('" & rsCPANezbirni("tipprod") & "')) AS BrojProd, Sum(Val('" & rsCPANezbirni("povrsina") & "')) AS p, Sum(Val('" & rsCPANezbirni("pmagacin") & "')) AS pm INTO T14_KPD_CPA_samo_podatoci FROM CPA_nezbirni WHERE (t4k" & Trim(Str(j)) & "<>'' Or t4k" & Trim(Str(j)) & " Is Not Null);"
Debug.Print "j = " & Str(j) & ", cpa select SQL: " & cpaSelectSQL
DoCmd.RunSQL cpaSelectSQL, True
On Error GoTo ErrorHandler
j = j + 1
Loop
The problem I have, only the last generated row gets copied in T14_KPD_CPA_samo_podatoci i.e cpa = 3
I want to copy each for for the value of cpa 1 to 3.
What do I do wrong?

SELECT INTO is a "Create table" query, it will overwrite the target table each time you run it.
Once the table exists you need INSERT INTO.

Well, I used this sort of SQL query
INSERT INTO table1 (col1, col2, ..., coln) SELECT col1, col2,..., coln FROM table2 WHERE condition GROUP BY colx;

Related

Run-time error ‘3061’: Too few parameters expected 1

i had this error when i was trying to INSERT records to a local table with VBA.
I have checked the data type and putting in the quotes for the the short text data type but it doesn't work.
table_newid = "SELECT Cint(t1." & id_name(i) & "_new), " & Replace(select_column_str, local_table_name, "t2") & " FROM " & vbCrLf & _
"(SELECT CInt(DCount(""[" & id_name(i) & "]"", """ & qry_distinct_id_name & """, ""[" & id_name(i) & "]<="" & [" & id_name(i) & "])) as " & id_name(i) & "_new, * FROM " & qry_distinct_id_name & ") AS t1 " & vbCrLf & _
"LEFT JOIN " & local_table_name & "_ALL as t2 " & vbCrLf & _
"ON t1." & id_name(i) & " = t2." & id_name(i) & " " & vbCrLf & _
"WHERE t2.database = '" & database_name & "'"
strQuery = "INSERT INTO " & local_table_name & "_temp (" & temp_field(i) & ", " & Replace(select_column_str, local_table_name & ".", "") & ") " & vbCrLf & table_newid
Debug.Print strQuery
DoCmd.SetWarnings False
db.Execute strQuery
DoCmd.SetWarnings True
From the debug.print, i have got:
INSERT INTO TblLUMachineTypes_temp (MachTypeID_new, MachTypeID, MachTypeCode, MachTypeMod, MachTypeDesc, MachTypeDisc, NewCode, Approved, mttime, CreatedBy, CreatedTS, ModifiedBy, ModifiedTS)
SELECT t1.MachTypeID_new, t2.MachTypeID, t2.MachTypeCode, t2.MachTypeMod, t2.MachTypeDesc, t2.MachTypeDisc, t2.NewCode, t2.Approved, t2.mttime, t2.CreatedBy, t2.CreatedTS, t2.ModifiedBy, t2.ModifiedTS FROM
(SELECT CInt(DCount("[MachTypeID]", "qry_TblLUMachineTypes_id_distinct", "[MachTypeID]<=" & [MachTypeID])) as MachTypeID_new, * FROM qry_TblLUMachineTypes_id_distinct) AS t1
LEFT JOIN TblLUMachineTypes_ALL as t2
ON t1.MachTypeID = t2.MachTypeID
WHERE t2.database = 'CPM-252-2'
When i copied this query and execute it manually, it works fine but not with VBA. Any idea?
Thanks in advance.
Remove all the & vbCrLf from your code, they are not necessary and I assume they corrupt the SQL syntax.
I found the problem. I found that qry_distinct_id_name query table has a Dlookup function in there that returns a string value, which will work when executing the query manual but doesn't work when you run it with VBA. So I have re-written the code to put in the quote before and after dlookup() function.

How to use multiple conditions which are variables in SQL in VBA code?

I am trying to run a select query statement like this in a table from VBA:
variable_a = 1
variable_b = 2
after proper database connection the query goes like:
SQry = "select CONCAT(Col1,Colb) as TOTAL from MyTable where Col1 = '" & variable_a & "' AND '" & variable_b & "'"
But it fails.\
How can I use that "AND" in between 2 or more statements which are variables of VBA? It works fine with one condition but the "AND" or "OR" part messes it up.
Thank you
Tried dividing the query into several lines like:
sq1 = "select CONCAT(Col1,Colb) AS TOTAL from MyTable" &
sq2 = "where Col1 = " & _
sq3 = " '" & variable_a & "'" & _
sq4 = " ' and ' " & _
sq5 = " Col2 = '" & variable_b & "'"

How Can I merge these two Access Sql queries

I want to merge these two queries into one query.
Here are the codes.
it's one table for both, but you see different data from different parts.
Just I want to make one record with only one query.
> DoCmd.RunSQL "insert into Report (id, [date], namep , [NEXTC],
> [Nurse])" & _ " values (" & Chr(34) & x & Chr(34) & " ," & Chr(34) & b
> & Chr(34) & "," & "5," & _ " " & Chr(34) & c & Chr(34) & ", " &
> Chr(34) & n & Chr(34) & ")"
and this one
DoCmd.RunSQL "INSERT INTO Report ( brand, Bag, Acc, Id , NameP)" & _
"Select Top 1 * from" & _
"(SELECT TOP 1 Brand FROM (SELECT * FROM Report WHERE ID=" & _
x & _
") WHERE Brand IS NOT NULL ORDER BY date DESC Union All SELECT top 1 null FROM report WHERE Brand IS NULL) AS Brand," & _
"(SELECT TOP 1 Bag FROM (SELECT * FROM Report WHERE ID=" & _
x & _
") WHERE Bag IS NOT NULL ORDER BY date DESC Union All SELECT top 1 null FROM report WHERE Bag IS NULL) AS Bag," & _
"(SELECT TOP 1 ACC FROM (SELECT * FROM Report WHERE ID=" & _
x & _
") WHERE ACC IS NOT NULL ORDER BY date DESC Union All SELECT top 1 null FROM report WHERE ACC IS NULL) AS ACC," & _
"(SELECT TOP 1 ID FROM Report WHERE ID=" & _
x & _
") AS ID," & _
"( SELECT TOP 1 NameP FROM Report WHERE ID=" & _
x & _
") as NameP;"
Test this, it should work (maybe some parentheses be wrong, check it before use):
DoCmd.RunSQL "insert into Report (id, [date], namep , [NEXTC], [Nurse], brand, Bag, Acc, Id , NameP)" & _
" values (" & Chr(34) & x & Chr(34) & " ," & Chr(34) & b & Chr(34) & "," & "5," & _
" " & Chr(34) & c & Chr(34) & ", " & Chr(34) & n & Chr(34) & ", " & _
"(SELECT TOP 1 Brand FROM (SELECT * FROM Report WHERE ID=" & x & _
") WHERE Brand IS NOT NULL ORDER BY date DESC Union All SELECT top 1 null FROM report WHERE Brand IS NULL) AS Brand " & ", " & _
"(SELECT TOP 1 Bag FROM (SELECT * FROM Report WHERE ID=" & x & _
") WHERE Bag IS NOT NULL ORDER BY date DESC Union All SELECT top 1 null FROM report WHERE Bag IS NULL) AS Bag " & ", " & _
"(SELECT TOP 1 ACC FROM (SELECT * FROM Report WHERE ID=" & x & _
") WHERE ACC IS NOT NULL ORDER BY date DESC Union All SELECT top 1 null FROM report WHERE ACC IS NULL) AS ACC " & ", " & _
"(SELECT TOP 1 ID FROM Report WHERE ID=" & x & ") AS ID," & _
"( SELECT TOP 1 NameP FROM Report WHERE ID=" & x & ") as NameP )"
Your query is not clear but your query should be something like this:
INSERT INTO Report (id, [date], namep , [NEXTC], [Nurse], brand, Bag, Acc, Id , NameP)
SELECT TOP 1 'value1', 'value2', ..., FROM yourTable ...
Using INSERT INTO SELECT
value1, value2 could be statistic but also you can get some value from yourtable

Using insert into where not exists in VBA

I have a lovely form and a lovely table in MS access (I promise). I would like to insert into this table at the press of a button using where not exists but I am getting a not-so-friendly run-time error 3067: "Query input must contain at least one table or query."
My query already does...
strSQL = "insert into tbl_MAP_systemTask (TaskID, SystemID) " & _
" Values (" & taskID & ", " & sysID & _
") where not exists " & _
" (select M.TaskID, M.SystemID from tbl_MAP_systemTask as M where M.TaskID = " & taskID & _
" and M.SystemID = " & sysID & ");"
Debug.Print strSQL
DoCmd.RunSQL (strSQL)
strSQL is now
insert into tbl_MAP_systemTask (TaskID, SystemID)
Values (1, 1)
where not exists
(select M.TaskID, M.SystemID
from tbl_MAP_systemTask as M where M.TaskID = 1 and M.SystemID = 1);
Can anyone shed any light on
a) what I broke?
b) how to fix it?
Well instead of using a SubQuery, you could use a Domain function to get this going,
If Dcount("*", "tbl_MAP_systemTask", "TaskID = " & taskID & " AND SystemID = " &sysID) = 0 Then
strSQL = "INSERT INTO tbl_MAP_systemTask (TaskID, SystemID) " & _
" VALUES (" & taskID & ", " & sysID & ")
CurrentDb.Execute strSQL
Else
MsgBox "The Data already exists in the table, so nothing was added."
End If
Try this:
strSQL = "insert tbl_MAP_systemTask (TaskID, SystemID) " & _
" select " & taskID & ", " & sysID & _
" where not exists " & _
" (select M.TaskID, M.SystemID from tbl_MAP_systemTask as M where M.TaskID = " & taskID & _
" and M.SystemID = " & sysID & ");"
=>
insert tbl_MAP_systemTask (TaskID, SystemID)
select 1, 1
where not exists
(select M.TaskID, M.SystemID
from tbl_MAP_systemTask as M where M.TaskID = 1 and M.SystemID = 1);
and seems to work in my case. Seems like the where not exists needs a select statement, so you have to model your insert like this.
Maybe you can use a recordset to insert these values.
Dim rs as Recordset
Set rs = Currentdb.openRecordset("SELECT * FROM tbl_MAP_systemTask WHERE TaskID=" & Me.TaskID & " AND SystemID=" & Me.SystemID)
if not (rs.eof or rs.bof) then
rs.addnew
rs.TaskID = Me.TaskID
rs.SystemID = Me.SystemID
rs.update
end if
rs.close
set rs = nothing
TOP 1 clause is must in the main query.
INSERT INTO tbl_MAP_systemTask (TaskID, SystemID)
SELECT TOP 1 1 AS TaskID 1 AS SystemID
FROM tbl_MAP_systemTask
WHERE NOT EXISTS (SELECT TOP 1 TaskID,SystemID FROM
tbl_MAP_systemTask WHERE TaskID = 1 and SystemID=1);
If tbl_MAP_systemTask table is empty or if there is only one record in the table then TOP 1 clause must be omitted in sub-query.
I have included Top 1 clause is sub-query for performance purpose.

Using Case Statement as second part of where clause

I have a current sql query I am using in vb.net to get some data returned to a datagridview. I am checking against the year, month and date of the date time picker to get the necessary information returned from the selected table. My query works fine minus the case statement part to check for specific dates. Can anyone help me fix this query or suggest an alternative method?
"SELECT * FROM " & Me.SelectedTable.SelectedItem.ToString & "
WHERE(Datepart(yyyy," & colName & ") BETWEEN '" & Me.DateTimePicker1.Value.Year & "' AND '" & Me.DateTimePicker2.Value.Year & "'
AND Datepart(mm," & colName & ") BETWEEN '" & Me.DateTimePicker1.Value.Month & "' AND '" & Me.DateTimePicker2.Value.Month & "'
AND Datepart(dd," & colName & ") <= " & Me.DateTimePicker1.Value.Day
& " CASE WHEN Datepart(mm," & colName & ")=" & Me.DateTimePicker1.Value.Month & "
THEN Datepart(dd," & colName & ") = " & Me.DateTimePicker1.Value.Day & "
WHEN Datepart(mm," & colName & ")= " & Me.DateTimePicker2.Value.Month
& " Datepart(dd," & colName & ")= " & Me.DateTimePicker2.Value.Day & "
ELSE Datepart(dd," & colName & ") BETWEEN 1 AND 31 END)"
First, your query is open to SQL injection attacks. You need to fix it by parameterizing your query.
Next, you do not need the CASE there: you can express your logic as a composite logical condition.
I changed the query from one that uses a dynamic column name defined by the value of the colName variable to use col for better readability. I also defined parameters for the values that come from various pickers. You will need to set them on your prepared command before querying.
The part of most interest is at the bottom: I rewrote your CASE as a three-part logical condition that evaluates one of three parts based on the settings of #month1 and #month2, which represent the month values from DateTimePicker1 and DateTimePicker2.
SELECT * FROM Table
WHERE (Datepart(yyyy, col) BETWEEN #year1 AND #year2
AND Datepart(mm, col) BETWEEN #month1 AND #month2
AND Datepart(dd, col) <= #day1
AND (
(Datepart(mm, col)=#month1 AND Datepart(dd, col) = #day1)
OR (Datepart(mm, col)=#month2 AND Datepart(dd, col) = #day2)
OR (Datepart(dd, col) BETWEEN 1 AND 31)
)
It looks like you have just forgotten then "THEN" at the end of your second condition.
So, make it:
CASE
WHEN Datepart(mm," & colName & ")=" & Me.DateTimePicker1.Value.Month & " THEN
Datepart(dd," & colName & ") = " & Me.DateTimePicker1.Value.Day & "
WHEN Datepart(mm," & colName & ")= " & Me.DateTimePicker2.Value.Month & " **THEN**
Datepart(dd," & colName & ")= " & Me.DateTimePicker2.Value.Day & "
ELSE Datepart(dd," & colName & ") BETWEEN 1 AND 31
END