Nested Select SQL statements in an Insert SQL statement - sql

I'm trying to take values from a Cart(ID PK, Username PK, MenuID) table and an Order(ID PK,Username,Address) table and insert them into an OrderItem(OrderID, MenuID, OrderItemID PK) table.
Its the process of confirming the purchase. So I have to insert all the values from the cart into OrderItem and add the last inserted ID in the Order table
Here's where I'm stuck:
insert into OrderItem (MenuID, OrderID) Values (A,B)
A=(Select MenuID from Cart Where Username='Foris')
B=(Select last_insert_rowid() from Order)
I added the B and A to explain what I meant. I can't do it using using inner joins i think.
Here's an image of the database design
Thanks in advance

Have you tried this?
insert into OrderItem (MenuID, OrderID)
Select MenuID, last_insert_rowid()
from Cart
Where Username = 'Foris';
I am not sure what select last_insert_rowid() from Order is supposed to be. Well, I do know, that would return all the rows in Order with one column, the last_insert_rowid() whatever that value might be.
The above assumes that the previous statement was an insert into Order.

Related

Foreach insert statement based on where clause

I have a scenario where I have thousands of Ids (1-1000), I need to insert each of these Ids once into a table with another record.
For example, UserCars - has columns CarId and UserId
I want to INSERT each user in my Id WHERE clause against CarId 1.
INSERT INTO [dbo].[UserCars]
([CarId]
,[UserId])
VALUES
(
1,
**My list of Ids**
)
I'm just not sure of the syntax for running this kind of insert or if it is at all possible.
As you write in the comments that my list of Ids is coming from another table, you can simply use select into with a select clause
See this for more information
insert into UserCars (CarID, UserID)
select CarID, UserID
from othertable
In the select part you can use joins and whatever you need, complex queries are allowed as long as the columns in the result match the columns (CarID, UserID)
or even this to keep up with your example
insert into UserCars (CarID, UserID)
select 1, UserID
from dbo.User
if your data exists on a file, you can use BULK INSERT command, for example:
BULK INSERT UserCars
FROM '\\path\to\your\folder\users-cars.csv';
Just make sure to have the same columns structure both in the file and in the table (e.g. CarId,UserId).
Otherwise, follow #GuidoG comment to insert your data from another table:
insert into UserCars (CarID, UserID) select CarID, UserID from othertable

Best approach to populate new tables in a database

I have a problem I have been working on the past several hours. It is complex (for me) and I don't expect someone to do it for me. I just need the right direction.
Problem: We had the tables (below) added to our database and I need to update them based off of data already in our DailyCosts table. The tricky part is that I need to take DailyCosts.Notes and move it to PurchaseOrder.PoNumber. Notes is where we currenlty have the PONumbers.
I started with the Insert below, testing it out on one WellID. This is Inserting records from our DailyCosts table to the new PurchaseOrder table:
Insert Into PurchaseOrder (PoNumber,WellId,JObID,ID)
Select Distinct Cast(Notes As nvarchar(20)), WellID, JOBID,
DailyCosts.DailyCostID
From DailyCosts
Where WellID = '24A-23'
It affected 1973 rows (The Notes are in Ntext)
However, I need to update the other new tables because we need to see the actual PONumbers in the application.
This next Insert is Inserting records from our DailyCost table and new PurchaseOrder table (from above) to a new table called PurchaseOrderDailyCost
Insert Into PurchaseOrderDailyCost (WellID, JobID, ReportNo, AccountCode, PurchaseOrderID,ID,DailyCostSeqNo, DailyCostID)
Select Distinct DailyCosts.WellID,DailyCosts.JobID,DailyCosts.ReportNo,DailyCosts.AccountCode,
PurchaseOrder.ID,NEWID(),0,DailyCosts.DailyCostID
From DailyCosts join
PurchaseOrder ON DailyCosts.WellID = PurchaseOrder.WellID
Where DailyCosts.WellID = '24A-23'
Unfortunately, this produces 3,892,729 records. The Notes field contains the same list of PONumbers each day. This is by design so that the people inputting the data out in the field can easily track their PO numbers. The new PONumber column that we are moving the Notes to would store just unique POnumbers. I modified the query by replacing NEWID() with DailyCostID and the Join to ON DailyCosts.DailyCostID = PurchaseOrder.ID
This affected 1973 rows the same as the first Insert.
The next Insert looks like this:
Insert Into PurchaseOrderAccount (WellID, JobID, PurchaseOrderID, ID, AccountCode)
Select PurchaseOrder.WellID, PurchaseOrder.JobID, PurchaseOrder.ID, PurchaseOrderDailyCost.DailyCostID,PurchaseOrderDailyCost.AccountCode
From PurchaseOrder Inner Join
PurchaseOrderDailyCost ON PurchaseOrder.ID = PurchaseOrderDailyCost.DailyCostID
Where PurchaseOrder.WellID = '24A-23'
The page in the application now shows the PONumbers in the correct column. Everything looks like I want it to.
Unfortunately, it slows down the application to an unacceptable level. I need to figure out how to either modify my Insert or delete duplicate records. The problem is that there are multiple foreign key constraints. I have some more information below for reference.
This shows the application after the inserts. These are all duplicate records that I am hoping to elminate
Here is some additional information I received from the vendor about the tables:
-- add a new purchase order
INSERT INTO PurchaseOrder
(WellID, JobID, ID, PONumber, Amount, Description)
VALUES ('MyWell', 'MyJob', NEWID(), 'PO444444', 500.0, 'A new Purchase Order')
-- link a purchase order with id 'A356FBF4-A19B-4466-9E5C-20C5FD0E95C3' to a DailyCost record with SeqNo 0 and AccountCode 'MyAccount'
INSERT INTO PurchaseOrderDailyCost
(WellID, JobID, ReportNo, AccountCode, DailyCostSeqNo, PurchaseOrderID, ID)
VALUES ('MyWell', 'MyJob', 4, 'MyAccount', 0, 'A356FBF4-A19B-4466-9E5C-20C5FD0E95C3', NEWID())
-- link a purchase order with id 'A356FBF4-A19B-4466-9E5C-20C5FD0E95C3' to an account code 'MyAccount'
-- (i.e. make it choosable from the DailyCost PO-column dropdown for any DailyCost record whose account code is 'MyAccount')
INSERT INTO PurchaseOrderAccount
(WellID, JobID, PurchaseOrderID, ID, AccountCode)
VALUES ('MyWell', 'MyJob', 'A356FBF4-A19B-4466-9E5C-20C5FD0E95C3', NEWID(), 'MyAccount')
-- link a purchase order with id 'A356FBF4-A19B-4466-9E5C-20C5FD0E95C3' to an AFE No. 'MyAFENo'
-- (same behavior as with the account codes above)
INSERT INTO PurchaseOrderAFE
(WellID, JobID, PurchaseOrderID, ID, AFENo)
VALUES ('MyWell', 'MyJob', 'A356FBF4-A19B-4466-9E5C-20C5FD0E95C3', NEWID(), 'MyAFENo')
So it turns out I missed some simple joining principles. The better I get the more silly mistakes I seem to make. Basically, on my very first insert, I did not include a Group By. Adding this took my INSERT from 1973 to 93. Then on my next insert, I joined DailyCosts.Notes on PurchaseOrder.PONumber since these are the only records from DailyCosts I needed. This was previously INSERT 2 on my question. From there basically, everything came together. Two steps forward an one step back. Thanks to everyone that responded to this.

How to perform insert for each selected row from database

I am trying to make stored procedure that:
- Get list of int rows
select ItemId from Items -- this returns: 1,2,3,4,5,6
In the second part of procedure I have to add row in another table for each of selected number. Something like:
foreach ItemId in previous result
insert into table (ItemIdInAnotherTable) values (ItemId)
UPDATE
I miss one important part from question.
In another part of procedure when I am inserting selected items in another table need to insert a few more columns. Something like this:
insert into dbo.ItemsNotificator
(UserId,ItemId)
(13879, (select ItemId from Items))
So it's not one column. Sorry for confusion :(
Edit :
Assuming that the table [table] already exists, and if User is a constant, then do like so:
INSERT INTO [table](UserId, ItemIdInAnotherTable)
SELECT 13879, ItemId
FROM Items;
If UserId comes from another table entirely, you'll need to figure out what relationship you need between UserId and ItemId. For instance, if all users are linked to all items, then it is:
INSERT INTO [table](UserId, ItemIdInAnotherTable)
SELECT u.UserId, i.ItemId
FROM Items i CROSS JOIN Users u;
If table [table] does NOT already exist, then you can use SELECT INTO, and specify a new table name (e.g. a #temp table stored in tempdb)
SELECT u.UserId, i.ItemId
INTO #tmpNewTable
FROM Items i CROSS JOIN Users u;
The columns in the newly created table will have the names UserId and ItemId and have the same types.
Looks simple to me:
INSERT INTO ItemIdInAnotherTable (ItemId)
SELECT ItemId from Items
That is exactly what a normal insert command does. Just do something like this:
insert into Table (ItemID)
select ItemID from Items;
use INSERT INTO..SELECT statement
INSERT INTO ItemIdInAnotherTable (ItemId)
SELECT ItemId
FROM Items

sql insert error

This is my Insert Statement
INSERT INTO ProductStore (ProductID, StoreID, CreatedOn)
(SELECT DISTINCT(ProductId), 1, GETDATE() FROM ProductCategory
WHERE EXISTS (SELECT StoreID, EntityID FROM EntityStore
WHERE EntityType = 'Category' AND ProductCategory.CategoryID = EntityStore.EntityID AND StoreID = 1))
I am trying to Insert into table ProductStore, all the Products Which are mapped to Categories that are mapped to Store 1. Column StoreID can definitely have more than one row with the same entry. And I am getting the following error: Violation of Primary Key Constraint...
However, the Following query does work:
INSERT INTO ProductStore (ProductID, StoreID, CreatedOn)
VALUES (2293,1,GETDATE()),(2294,1,GETDATE())
So apparently, the ProductID Column is trying to insert the same one more than once.
Can you see anything wrong with my query?
TIA
I don't see any part of that query that excludes records already in the table.
Take out the INSERT INTO statement and just run the SELECT - you should be able to spot pretty quickly where the duplicates are.
My guess is that you're slightly mistaken about what SELECT DISTINCT actually does, as evidenced by the fact that you have parentheses around the ProductId. SELECT DISTINCT only guarantees the elimination of duplicates when all columns in the select list are the same. It won't guarantee in this case that you only get one row for each ProductId.
select distinct productid is selecting an existing ID and therefor in violation with your primary key constraint.
Why don't you create the primary key using Identity increment? In that case you don't need to worry about the ID itself, it will be generated for you.

Increment non unique field during SQL insert

I'm not sure how to word this cause I am a little confused at the moment, so bear with me while I attempt to explain, I have a table with the following fields:
OrderLineID, OrderID, OrderLine, and a few other unimportant ones.
OrderLineID is the primary key and is always unique (which isn't a problem), OrderID is a foreign key that isn't unique (also not a problem), and OrderLine is a value that is not unique in the table, but should be unique for any OrderIDs that are the same...so if that didn't make sense, perhaps a picture...
OrderLineID, OrderID, OrderLine
1 1 1
2 1 2
3 1 3
4 2 1
5 2 2
For all OrderIDs there is a unique OrderLine. I am trying to create an insert statement that gets the max OrderLine value for a specific OrderId so I can increment it, but it's not working so well and I could use a little help. What I have right now is below, I build the SQL statement in a program and replace OrderID # with an actual value. I am pretty sure the problem is with the nested select statement, and incrementing the result, but I can't find any examples that do this since my Google skills are weak apparently....
INSERT INTO tblOrderLine (OrderID, OrderLine) VALUES
(<OrderID #>, (SELECT MAX(OrderLine)
FROM tblOrderLine WHERE orderID = <same OrderID #>)+1)
Any help would be nice.
This statement works in Access 2003. You would have to substitute your OrderID value in the WHERE clause.
INSERT INTO tblOrderLine (OrderID, OrderLine)
SELECT
s.OrderID,
s.MaxOrderLine + 1 AS NewOrderLine
FROM (
SELECT
OrderID,
Max(OrderLine) AS MaxOrderLine
FROM
tblOrderLine
WHERE
OrderID=1
GROUP BY
OrderID
) AS s;
I read the others' misgivings, and will leave the wisdom of this approach to you. It could get more interesting if you can have multiple users updating tblOrderLine at the same time.
Are you getting some type of error? Your SQL code seems to work fine for me.
Don't use a combination of VALUES and SELECT. Try:
INSERT INTO tblOrderLine (OrderID, OrderLine)
SELECT <OrderID #>, MAX(OrderLine)
FROM tblOrderLine
WHERE orderID = <same OrderID #>)+1
;
Adding a scalar to the result of a query isn't generally kosher. Try moving the "+1":
INSERT INTO tblOrderLine (OrderID, OrderLine) VALUES
(
<OrderID #>,
(SELECT MAX(OrderLine)+1 FROM tblOrderLine WHERE orderID = <OrderID #>)
)