VBA INSERT FROM a table and also from a form - vba

I am new to using VBA code and am having trouble getting a full piece of code to run.
I am trying to complete an insert into a table "SmallItems" taking existing fields from table "SmallItemsImport" but also inserting new fields that i want left blank for later use, and also taking the 2 values from a form and inserting them into fields in the "SmallItems" table.
SmallItemsImport table fields = ItemNo, Caseworker, VSSID, ItemDescription, Framework, Amount
Extra fields I want inserted and left blank = QueryDate, QueryUser, VouchedDate, VouchedUser, Status
Fields I wanted created and values taken from form drop downs = Organisation, ReturnDate
I have tried the following code but it would not work:
strSQL = "INSERT INTO SmallItems ( Organisation, ReturnDate, ItemNo, Caseworker, ID, ItemDescription, Framework, Amount, QueryDate, QueryUser, VouchedDate, VouchedUser, Status ) SELECT Forms![SmallItemsImportValidationForm]![OrganisationDropDown]" & ", [SmallItemsImportValidationForm]![ReturnDateDropDown]" & " ,[SmallItemsImport].ItemNo, [SmallItemsImport].Caseworker, [SmallItemsImport].ID, [SmallItemsImport].ItemDescription, [SmallItemsImport].Framework, [SmallItemsImport].Amount " & "FROM [SmallItemsImport]"
Any Help Appreciated. Thanks

By including them in the insert clause, you are telling your DB to expect a value for fields QueryDate, QueryUser, VouchedDate, VouchedUser, Status
INSERT INTO SmallItems ( Organisation, ReturnDate, ItemNo, Caseworker,
ID, ItemDescription, Framework, Amount,
QueryDate, QueryUser, VouchedDate, VouchedUser, Status )
however in your select you dont supply a corresponding value for the last 5 fields, so you have a mismatch (number fields in insert <> number fields in select) so either ...
Add literal values to your select statement corresponding to the fields (for illustration I'm using Null but could be anything you want)
SELECT ... , [SmallItemsImport].Amount, Null, Null, Null, Null, Null FROM ...
or
Just leve them out of the insert clause and let the DB create a default value
INSERT INTO SmallItems ( Organisation, ReturnDate, ItemNo,
Caseworker, ID, ItemDescription, Framework, Amount)

I got it resolved, after adding in the Null values, I was missing the word "Forms" before the ReturnDate SELECT, after adding this it worked as I wanted.
strSQL = "INSERT INTO SmallItems ( Organisation, ReturnDate, ItemNo, Caseworker, ID, ItemDescription, Framework, Amount, QueryDate, QueryUser, VouchedDate, VouchedUser, Status ) SELECT Forms![SmallItemsImportValidationForm]![OrganisationDropDown]" & ", Forms![SmallItemsImportValidationForm]![ReturnDateDropDown]" & " ,[SmallItemsImport].ItemNo, [SmallItemsImport].Caseworker, [SmallItemsImport].ID, [SmallItemsImport].ItemDescription, [SmallItemsImport].Framework, [SmallItemsImport].Amount, Null, Null, Null, Null, Null " & "FROM [SmallItemsImport]"
Thanks for the replies.

Related

'Enter parameter value' in insert statement

I have 2 tables Project Tracking(pkID as primary) and Status log(pkidStatus as primary and is auto generated and fkidProject, ProjectStatus, StatusDate).
The SurveyRequestIntakeForm has records from ProjectTracking with the pkID field.
The 'Add status Log Entry' button Should run the append query and add a row to the “StatusLog” table – feeding the pkID from the form to the fkProjectid field in the table StatusLog.
INSERT INTO StatusLog ( fkidProject, ProjectStatus, StatusDate )
SELECT ProjectTracking.pkID, "Start" AS Expr1, Date() AS Expr2
FROM ProjectTracking
WHERE (((ProjectTracking.pkID)=[Forms]![SurveyRequestIntakeForm]![pkID]));
When this query runs it shows enter parameter value [Forms]![SurveyRequestIntakeForm]![pkID]
SurveyRequestIntakeForm
Try this:
INSERT INTO StatusLog ( fkidProject, ProjectStatus, StatusDate )
VALUES ( [Forms]![SurveyRequestIntakeForm]![pkID] , "Start", Date())

hardcode item to list in oracle

I have the following query which lists items in a specific order that I wanted. Now I want to hard code a value to be displayed along with the other values but this value doesn't exist in my table and I don't want to add it.
Here's the query:
select item_name from item_table
order by
case
when item_name = 'New' then 1
when item_name = 'In Progress' then 2
when item_name = 'Passed' then 3
when item_name = 'Exempt' then 4
else 5
end, item_name;
Expected results that I need
New
In Progress
Passed
Expired
Exempt
Actual results that I am getting:
New
In Progress
Passed
Exempt
Is there a way to hardcode Expired along with the other items to be displayed when I run the query?
Table ddl used and insert statement.
CREATE TABLE ITEM_TABLE
( ITEM_NAME VARCHAR2(20 CHAR)
) ;
Insert into ITEM_TABLE (ITEM_NAME) values ('NEW');
Insert into ITEM_TABLE (ITEM_NAME) values ('In Progress');
Insert into ITEM_TABLE (ITEM_NAME) values ('passed');
Insert into ITEM_TABLE (ITEM_NAME) values ('Exempt');
If I understand you correctly. This should do it.
SELECT
*
FROM
(
SELECT
item_name
FROM
item_table
UNION
SELECT
'hard_coded_Value' item_name
FROM
item_table
)
ORDER BY
CASE
WHEN item_name = 'New' THEN
1
WHEN item_name = 'In Progress' THEN
2
WHEN item_name = 'Passed' THEN
3
WHEN item_name = 'Exempt' THEN
4
WHEN ITEM_NAME = 'hard_coded_Value' then
5
ELSE
6
END,
item_name;
I can't really validate the query since you haven't provided some ddl to test with but this is the generally how I would tackle a problem like this.

Column Not Allowed SQL

Error Code Screenshot (ShipDate is now the error)
For my school project we are to create a product database where the customer places an order etc. I've compared my code to classmates and it's the essentially the same except I have less columns. This section of the code inserts the user input into the Orders Table.
The 2nd to last Column, OrderStatus, is where the * appears in the console. I apologize ahead of time if it looks messy, for some reason the format in the Body doesn't carry over to publish posts.
CODE:
INSERT INTO Orders
VALUES (OrderNum,
OrderDate,
CustID,
PNum,
UnitPrice,
QtyOrder,
TotalCost,
ShipDate,
QtyShipped,
OrderStatus,
NULL);
SELECT MaxNum,
SYSDATE,
&vCustID,
'&vPNum',
UnitPrice,
&vQty,
TotalCost,
ShipDate,
QtyShipped,
'Open',
Orders.ReasonNum
FROM CancelledOrder, Orders, Counter
WHERE Orders.ReasonNum = CancelledOrder.ReasonNum;
COMMIT;
Orders Table for reference
CREATE TABLE Orders
(
OrderNum NUMBER (4) PRIMARY KEY,
OrderDate DATE,
CustID CHAR (3),
PNum VARCHAR2 (3),
UnitPrice NUMBER,
QtyOrder NUMBER,
TotalCost NUMBER,
ShipDate DATE,
QtyShipped NUMBER,
OrderStatus VARCHAR2 (10),
ReasonNum NUMBER,
CONSTRAINT fk_CustID FOREIGN KEY (CustID) REFERENCES Customer (CustID),
CONSTRAINT fk_PNum FOREIGN KEY (PNum) REFERENCES Product (PNum),
CONSTRAINT fk_ReasonNum FOREIGN KEY
(ReasonNum)
REFERENCES CancelledOrder (ReasonNum)
);
I presume that INSERT should go along with SELECT, i.e.
insert into ...
select ... from
On your example:
INSERT INTO Orders (OrderNum, --> no VALUES keyword, but list of columns
OrderDate,
CustID,
PNum,
UnitPrice,
QtyOrder,
TotalCost,
ShipDate,
QtyShipped,
OrderStatus,
reasonnum) --> reasonnum instead of null
SELECT MaxNum,
SYSDATE,
&vCustID,
'&vPNum',
UnitPrice,
&vQty,
TotalCost,
ShipDate,
QtyShipped,
'Open',
Orders.ReasonNum
FROM CancelledOrder, Orders, Counter
WHERE Orders.ReasonNum = CancelledOrder.ReasonNum;
Also, check FROM & WHERE clauses: there are 3 tables involved with only one condition. You'll get - as a result - more rows than you expected, unless you fix that (or unless COUNTER table contains only 1 row).
For these examples, imagine two tables, a and b, with 3 columns each.
When you are inserting, the statement must either use:
Method A) Here we instruct the database to INSERT (to all or to specific columns) the results of a query. To do this, we write INSERT INTO SELECT ..... for example:
INSERT INTO table_a select table_b.* from table_b --Useful when we know how many columns table a and b have;
or
INSERT INTO table_a select b.column_2, b.column_3, b.column_1 from table_b --Usefull if b had more columns and we want those three, or if the order of the columns of b needs id different from the order of the columns of a
[In this case, all columns of table a will be filled with the respective columns from the rows of table b that the select part of the query returns]
or:
INSERT INTO table_a (tab_a_column1, tab_a_column3) select b.column_1, b.column_3 from table_b
[In this case, only the specified columns of table a will be filled with the columns from table b that the select part of the query returns]
-> Note that in these examples the VALUES keyword is never used
Method B) In this case we instruct the database to insert a sinlge new row with specific values into the table (to all or to specific columns of the table). In this method we do not use a select query at all:
INSERT INTO table_a VALUES ( 1, 'asdf', 5658 ) ;
In this example we just give some values to be inserted. They will be put in the corresponding columns of table_a, in the order that the columns are in the table.
INSERT INTO table_a (tab_a_column1, tab_a_column3) VALUES (1, 5658);
The numbers 1 and 5658 will be inserted to the first and third column, while the second one will be left NULL
So, when using VALUES, we are only inserting one row.
But when using Method A, our one statement may insert any number of rows at one go. It all will depend on how many rows the SELECT part of the query returns.
NOTE: the select part of the query in method A has no limit to how complex it can be. For example it can have multiple joins, where clauses, group by ... and more.
A good link that explains INSERT INTO can be found here:
https://www.techonthenet.com/sql/insert.php

Unable to use multiple select statements to insert data into a table

So I'm trying to insert data into the Main_Contract_Data table from three different tables and it is producing an error that is shown below, does anyone know why?
Error:
Msg 120, Level 15, State 1, Line 1
The select list for the INSERT statement contains fewer items than the insert list. The number of SELECT values must match the number of INSERT columns.
//SQL Server 2008 Code
INSERT INTO Main_Contract_Data
(organisation_name,
contract_start_date,
a_manager,
d_manager)
(SELECT [Client]
FROM [Internal].[dbo].[RequiredFields$])
(SELECT [Start Date]
FROM [Internal].[dbo].[RequiredFields$])
(SELECT person_id
FROM A_Manager
WHERE person_id = '5')
(SELECT person_id
FROM D_Manager
WHERE person_id = '6')
You just need to make those sub queries:
INSERT INTO Main_Contract_Data
(organisation_name,
contract_start_date,
a_manager,
d_manager)
SELECT
(SELECT [Client]
FROM [Internal].[dbo].[RequiredFields$]),
(SELECT [Start Date]
FROM [Internal].[dbo].[RequiredFields$]),
(SELECT person_id
FROM A_Manager
WHERE person_id = '5'),
(SELECT person_id
FROM D_Manager
WHERE person_id = '6')
But keep in mind that each sub query can only return one row, while the overall query needs to return an entire result set. If that's only one row too, that's fine, but the overall SELECT is to return one or more while each sub query returns one row, and one value for each row in the overall query.

Insert values into table from the same table

Using SQL server (2012)
I have a table - TABLE_A with columns
(id, name, category, type, reference)
id - is a primary key, and is controlled by a separte table (table_ID) that holds the the primary next available id. Usually insertions are made from the application side (java) that takes care of updating this id to the next one after every insert. (through EJBs or manually, etc..)
However,
I would like to to write stored procedure (called from java application) that
- finds records in this table where (for example) reference = 'AAA' (passed as
parameter)
- Once multiple records found (all with same reference 'AAA', I want it to INSERT new
records with new ID's and reference = 'BBB', and other columns (name, category, type)
being same as in the found list.
I am thinking of a query similar to this
INSERT INTO table_A
(ID
,NAME
,CATEGORY
,TYPE,
,Reference)
VALUES
(
**//current_nextID,**
(select NAME
from TABLE_A
where REFENCE in (/*query returning value 'AAA' */),
(select CATEGORY
from TABLE_A
where REFENCE in (/*query returning value 'AAA' */),
(select TYPE
from TABLE_A
where REFENCE in (/*query returning value 'AAA' */),
'BBB - NEW REFERENCE VALUE BE USED'
)
Since, I don't know how many records I will be inserting , that is how many items in the result set of a criteria query
select /*field */
from TABLE_A
where REFENCE in (/*query returning value 'AAA' */),
I don't know how to come up with the value of ID, on every record. Can anyone suggest anything, please ?
It's not clear from your question how sequencing is handled but you can do something like this
CREATE PROCEDURE copybyref(#ref VARCHAR(32)) AS
BEGIN
-- BEGIN TRANSACTION
INSERT INTO tablea (id, name, category, type, reference)
SELECT value + rnum, name, category, type, 'BBB'
FROM
(
SELECT t.*, ROW_NUMBER() OVER (ORDER BY id) rnum
FROM tablea t
WHERE reference = 'AAA'
) a CROSS JOIN
(
SELECT value
FROM sequence
WHERE table_id = 'tablea'
) s
UPDATE sequence
SET value = value + ##ROWCOUNT + 1
WHERE table_id = 'tablea'
-- COMMIT TRANSACTION
END
Sample usage:
EXEC copybyref 'AAA';
Here is SQLFiddle demo