I'm trying to write a shopping basket into a order + orderline in a sql database from C# asp.net.
the orderline will contain a ordernumber, total price, productid, quantity etc. for every item in the basket. The order itself will contain the ordernumber as primary key and will be linked to the different lines through it.
Everything worked fine yesterday, but now as i tried to use a SELECT command in the insert into statement to get things more dynamic i'm getting the above described syntax error.
Does anybody know what's wrong with this statement:
INSERT INTO [order]
(klant_id,totaalprijs,btw,subtotaal,verzendkosten)
SELECT klant.id
, SUM(orderregel.totaalprijs)
, SUM(orderregel.btw)
, SUM(orderregel.totaalprijs) - SUM(orderregel.btw)
, 7.50
FROM orderregel
INNER JOIN
klant
ON [order].klant_id = klant.id
WHERE klant.username = 'jerry'
GROUP BY
id;
the ordernumber in the "order" table is on autonumber, in the asp codebehind there is a for each which handles the lines being written for every product, there's an index set on 0 outside of this loop and is heightened with 1 every end of it. The executenonquery of the order is only executed once at the beginning of the first loop and the lines are added after with MAX(ordernumber) as ordernumber.
I hope i have provided enough information and somebody is capable of helping me.
Thanks in advance!
EDIT:
thanks everybody, using this query did it!
INSERT INTO [order]
(klant_id,totaalprijs,btw,subtotaal,verzendkosten) SELECT (SELECT klant.id FROM klant WHERE klant.username = 'jerry') ,
SUM(orderregel.totaalprijs) , SUM(orderregel.btw) ,
SUM(orderregel.totaalprijs) - SUM(orderregel.btw) , 7.50 FROM
orderregel;
You have used [order] in a JOIN, when it should be orderregel I guess.
FROM orderregel
INNER JOIN klant ON [order].klant_id = klant.id
should be:
FROM orderregel
INNER JOIN klant ON orderregel.klant_id = klant.id
Edit:
Why not just using:
INSERT INTO [order]
(klant_id,totaalprijs,btw,subtotaal,verzendkosten)
SELECT (SELECT klant.id FROM klant WHERE klant.username = 'jerry')
, SUM(orderregel.totaalprijs)
,...
... and avoid JOIN with klant table?
You can't refer to the table being inserted into. After all, those rows aren't yet there before the insert completes!
Reading your query, it's clear that you're trying to insert the klant called Jerry. But how do you specify which orderlines are used for the insert?
A possible solution:
Write the order first, with the klant id
Create the order lines. You know the orderid from the first query (f.e. using select SCOPE_IDENTITY()
Update the order with totals
Try this:
INSERT INTO [order]
(klant_id,totaalprijs,btw,subtotaal,verzendkosten)
SELECT klant.id
, SUM(orderregel.totaalprijs)
, SUM(orderregel.btw)
, SUM(orderregel.totaalprijs) - SUM(orderregel.btw)
, 7.50
FROM orderregel
INNER JOIN klant ON orderregel.id = klant.id
INNER JOIN [order] ON [order].klant_id = klant.id
WHERE klant.username = 'jerry'
GROUP BY id;
Related
I want to insert some data in Table1 in my database selecting it from another Table2 but the Table1 has another attribute for username (ComputerName).
What I have tried:
INSERT INTO [AffecAnalytique].[dbo].[C9_V] ([C9], [V], [OID], [USERMODIF])
SELECT [C9], [V], [OID] FROM [AffecAnalytique].[dbo].[C9_V]
WHERE [OID] = 'CEC4F038E3954AC79DBF7EC38B02171F' , 'AHE'
I think you are looking for something like this :
INSERT INTO [AffecAnalytique].[dbo].[C9_V] ([C9], [V], [OID], [USERMODIF])
SELECT [C9], [V], [OID], 'AHE' FROM [AffecAnalytique].[dbo].[C9_V]
WHERE [OID] = 'CEC4F038E3954AC79DBF7EC38B02171F'
I want to retrieve data from two tables like below. I have a Products table which has P_id, P_name columns and a BATCH table with p_id_fk as a foreign key to the Products table.
This is my query; I want to retrieved from product's name from the Product table because I have stored the Products table primary key as a foreign in the Batch table.
SqlDataAdapter sda = new SqlDataAdapter("Select batch_id, quantity, left_qty, purchaseDate, manufacturing_date, expiryDate from batch where Convert(DATE, expiryDate, 103) BETWEEN #from AND #to", con);
sda.SelectCommand.Parameters.AddWithValue("#from", Convert.ToDateTime(datePicker1.SelectedDate.Value).ToString("yyyyMMdd"));
sda.SelectCommand.Parameters.AddWithValue("#to", Convert.ToDateTime(datePicker2.SelectedDate.Value).ToString("yyyyMMdd"));
If you want to retrieve data from two tables you need to use a SQL JOIN
I am not sure of the exact make up of your tables but something like the below
Select batch_id,
product_name,
quantity,
left_qty,
purchaseDate,
manufacturing_date,
expiryDate
from batch B
INNER JOIN Products P
ON P.P_id = B.P_id
where Convert(DATE,expiryDate,103) BETWEEN #from AND #to
you need to have a join or cross apply here.
Option 1 - inner join:
Select
b.batch_id,pd.product_name,quantity,left_qty,
purchaseDate,manufacturing_date,expiryDate from batch b
inner join product pd on pd.p_id = b.p_id where Convert(DATE,expiryDate,103)
BETWEEN #from AND #to
Option 2 cross apply:
Select
b.batch_id,pd.product_name,quantity,left_qty,
purchaseDate,manufacturing_date,expiryDate from batch b
cross apply
(
select product_name from product p
where p.p_id = b.p_id
) pd
where Convert(DATE,expiryDate,103)
BETWEEN #from AND #to
for more about cross apply look here.
Not sure if I understood your question correctly, but I believe for your query you are looking for something simple as JOIN between Products and Batch tables:
SELECT
P.P_id,
P.P_name,
B.batch_id,
B.product_name,
B.quantity,
B.left_qty,
B.purchaseDate,
B.manufacturing_date,
B.expiryDate
FROM Batch AS B
INNER JOIN Products AS P
ON B.p_id_fk = P.P_id
WHERE CONVERT(DATE, B.expiryDate, 103) BETWEEN #from AND #to
p_id_fk name you provided might be not an actual column name in Batch table but rather the name of the foreign key constraint itself as it appears by the naming convention (_fk suffix).
I am creating a web app in which i am using insert into select command
for which i have taken a stored procedure which looks like this
alter PROCEDURE profinalinstexpensesonid
(
#from varchar(5000),
#to varchar(5000),
#trainer varchar(5000),
#sonvinid varchar(5000),
#button varchar(5000),
#bill_id varchar(5000)
)
AS
BEGIN
if(#button='allselect')
begin
insert into listinvoice(sonvinid,tid,date,brandname,zone,location,area,venuename,venue,instructore,amount)
select
instructoreexpense.sonvinid,
sonvininsert.trainer,
convert(varchar,sonvininsert.date,105) as date ,
sonvininsert.brandname,
substring(sonvininsert.zone,1,1)as zone,
sonvininsert.location,
sonvininsert.area,
companysonvinunitvenue.venuename,
sonvininsert.venue,
sonvininsert.instructore,
instructoreexpense.amount
from
instructoreexpense
left outer join sonvininsert on
sonvininsert.sonvinid=instructoreexpense.sonvinid and
sonvininsert.status='0'
left outer join finalinstructoreexpense on
finalinstructoreexpense.sonvinid=instructoreexpense.sonvinid
left outer join companysonvinunitvenue on
companysonvinunitvenue.id=sonvininsert.comsonvinid
where
sonvininsert.sonvinid not in(select sonvinid from listinvoice)
and
sonvininsert.date
between convert(datetime,#from,105) and
convert(datetime,#to,105) and
sonvininsert.trainer=(select empname from trainerdetails where trid=#trainer)
and instructoreexpense.sonvinid NOT IN (
SELECT CAST(Item AS INTEGER)
FROM SplitString(#sonvinid, ',')
)
order by instructoreexpense.sonvinid
end
end
now this is working absolutely fine, now on this line
insert into listinvoice(sonvinid,tid,date,brandname,zone,location,area,venuename,venue,instructore,amount)
i want to add bill_id
and i will get my bill_id from a textbox in my program
so i want to change this line into something like this
insert into listinvoice(sonvinid,tid,date,brandname,zone,location,area,venuename,venue,instructore,amount,bill_id=#bill_id)
but i am gettig the error of
Msg 102, Level 15, State 1, Procedure profinalinstexpensesonid, Line
14 Incorrect syntax near '='.
what i need to do,
i am getting bill_id from my textbox,
is there any other options???
The problem is with your INSERT statement:
insert into listinvoice(sonvinid,tid,date,brandname,zone,
location,area,venuename,venue,instructore,amount,bill_id=#bill_id)
You haven't finished the statement. You would typically format it like this:
INSERT INTO (Col1, Col2, Col3) VALUES (#Val1, #Val2, #Val3)
You would first list the columns for which you want to provide values in the first group and then list the values themselves in the second group after the keyword VALUES).
In yours, you appear to be listing the columns you want to insert with the exception of the last one, where you're trying to also assign a value somehow. You need something like this:
insert into listinvoice(sonvinid,tid,date,brandname,zone,
location,area,venuename,venue,instructore,amount,bill_id)
VALUES (#sonvinid, ..., #bill_id)
Obviously you'd replace the ellipsis with your actual parameters.
You have to change your statement. You are currently doing this:
insert into listinvoice(sonvinid,tid,date,brandname,zone,location,area,venuename,venue,instructore,amount,bill_id=#bill_id)
Where it should be something like this:
insert into listinvoice(sonvinid,tid,date,brandname,zone,location,area,venuename,venue,instructore,amount,bill_id)
select
instructoreexpense.sonvinid,
sonvininsert.trainer,
convert(varchar,sonvininsert.date,105) as date ,
sonvininsert.brandname,
substring(sonvininsert.zone,1,1)as zone,
sonvininsert.location,
sonvininsert.area,
companysonvinunitvenue.venuename,
sonvininsert.venue,
sonvininsert.instructore,
instructoreexpense.amount,
#bill_id
from
instructoreexpense
left outer join sonvininsert on
sonvininsert.sonvinid=instructoreexpense.sonvinid and
sonvininsert.status='0'
left outer join finalinstructoreexpense on
finalinstructoreexpense.sonvinid=instructoreexpense.sonvinid
left outer join companysonvinunitvenue on
companysonvinunitvenue.id=sonvininsert.comsonvinid
where
sonvininsert.sonvinid not in(select sonvinid from listinvoice)
and
sonvininsert.date
between convert(datetime,#from,105) and
convert(datetime,#to,105) and
sonvininsert.trainer=(select empname from trainerdetails where trid=#trainer)
and instructoreexpense.sonvinid NOT IN (
SELECT CAST(Item AS INTEGER)
FROM SplitString(#sonvinid, ',')
)
order by instructoreexpense.sonvinid
LAYOUT:
I have a Subscriber database with Subscriber info in a table, all with unique AccountID's.
I have multiple History databases with a History table in each, all pertaining to the AccountID's in the Subscriber database.
I NEED:
I need a list of the most recent History record entered, in any of the History databases, for each AccountID in the Subscriber data. 1 record per AccountID.
I can achieve this with multiple hits to the database, but there are potentially millions of records and that doesn't sit well in my head. I want to make this happen in one hit.
Help. Me. Thanks.
Here's something I have tried already, but it doesn't give me a single record per AccountID...
SELECT
MAIN.*,
ISNULL(SubData.Name, '') AS [Name],
ISNULL(SubData.AcctLineCode, '') AS AcctLineCode,
ISNULL(LTRIM(RTRIM(SubData.AcctNum)), '') AS AcctNum
FROM
(
SELECT AccountID, AlarmDate, AlarmCode FROM [History1113]..SignalHistory WHERE AccountID IN (SELECT DISTINCT AccountID FROM Subscriber..[Subscriber Data])
UNION
SELECT AccountID, AlarmDate, AlarmCode FROM [History1013]..SignalHistory WHERE AccountID IN (SELECT DISTINCT AccountID FROM Subscriber..[Subscriber Data])
UNION
SELECT AccountID, AlarmDate, AlarmCode FROM [History0913]..SignalHistory WHERE AccountID IN (SELECT DISTINCT AccountID FROM Subscriber..[Subscriber Data])
)
AS MAIN
LEFT JOIN Subscriber..[Subscriber Data] AS SubData ON Main.AccountID = SubData.AccountID
ORDER BY AccountID, AlarmDate DESC
I'd do it as a view. Biggest issue will be making sure the view can see all the history tables if they are in seperate databases. You may have to get into linked servers
Create view historytable
as
select * from historytable1
union all
select * from historytable2
union all
etc...
Now query from historytable as if it was a table with all rows in it.
Edit:
the statement you've added has no aggregates, so it has no method of filtering down (or grouping by) into one record.
To your reply:
Lets call my view above main so I don't have to type so much.
Select account_id, max(alarm_date) as maxdate from main group by account_id
This simple select brings back to most recent record. Inner join it so it functions as a filter.
select ...
from main
inner join (Select account_id, max(alarm_date) as maxdate from main group by account_id) maxdate
on main.account_id = maxdate.account_ID and maxdate.maxdate = main.alarm_date
Add your subscriber join to the bottom of that and fill in the columns you need
With a little help from a couple of you, I was able to figure this out. So, thank you all.
Here's a code snippet of how I got it to work. I still need to do some joins to bring in account info, but this was the hard part.
`
SELECT MAIN.AccountID, MAX(MAIN.AlarmDate) AS AlarmDate FROM
(
SELECT AccountID, MAX(AlarmDate) AS AlarmDate FROM [History1113]..SignalHistory WHERE AccountID IN (SELECT DISTINCT AccountID FROM Subscriber..[Subscriber Data])
GROUP BY AccountID
UNION
SELECT AccountID, MAX(AlarmDate) AS AlarmDate FROM [History1013]..SignalHistory WHERE AccountID IN (SELECT DISTINCT AccountID FROM Subscriber..[Subscriber Data])
GROUP BY AccountID
UNION
SELECT AccountID, MAX(AlarmDate) AS AlarmDate FROM [History0913]..SignalHistory WHERE AccountID IN (SELECT DISTINCT AccountID FROM Subscriber..[Subscriber Data])
GROUP BY AccountID
)
AS MAIN
GROUP BY MAIN.AccountID
`
i am trying to show the last order for the a specific customer on a grid view , what i did is showing all orders for the customer but i need the last order
here is my SQL code
SELECT orders.order_id, orders.order_date,
orders.payment_type, orders.cardnumber, packages.Package_name,
orders.package_id, packages.package_price
FROM orders INNER JOIN packages ON orders.package_id = packages.Package_ID
WHERE (orders.username = #username )
#username get its value from a cookie , now how can i choose the last order only for a cookie value " Tony " for example ?
To generalize (and fix a little bit) Mitch's answer, you need to use SELECT clause embellished with TOP(#N) and ORDER BY ... DESC. Note that I use TOP(#N), not TOP N, which means you can pass it as an argument to the stored procedure and return, say, not 1 but N last orders:
CREATE STORED PROCEDURE ...
#N int
...
SELECT TOP(#N) ...
ORDER BY ... DESC
SELECT top 1
orders.order_id,
orders.order_date,
orders.payment_type,
orders.cardnumber,
packages.Package_name,
orders.package_id,
packages.package_price
FROM orders
INNER JOIN packages ON orders.package_id = packages.Package_ID
WHERE (orders.username = #username )
ORDER BY orders.order_date DESC
In fact assuming orders.order_id is an Identity column:
SELECT top 1
orders.order_id,
orders.order_date,
orders.payment_type,
orders.cardnumber,
packages.Package_name,
orders.package_id,
packages.package_price
FROM orders
INNER JOIN packages ON orders.package_id = packages.Package_ID
WHERE (orders.username = #username )
ORDER BY orders.order_id DESC