开发者

how to copy some columns from deferent tables into another table using sql statement

开发者 https://www.devze.com 2023-03-07 06:15 出处:网络
I am very stressful with Sql coding. Any solut开发者_如何学Cion please help.... I have tables like below :

I am very stressful with Sql coding. Any solut开发者_如何学Cion please help.... I have tables like below :

  OrderedFood(**TableID,FoodID**,Qty,OrderedDate)
  Invoices(**InvoiceID**,TableID,Amount)
  InvoiceDetail(**InvoiceID,FoodID**,Qty,orderedDate)

I want to copy OrderedFood.TableID => Invoices.TableID. then copy OrderedFood.FoodID => InvoiceDetail.FoodID , OrderedFood.Qty => InvoiceDetail.Qty which this content a lot of rows.

How could i do it ?

Thanks in advance ...


I'm afraid it is a bit hard to understand exactly what you are trying to do. Hopefully the following SQL can help point you in the right direction

DECLARE @OrderedFood Table(TableID int ,FoodID int ,Qty int ,OrderedDate datetime)
DECLARE @Invoices Table(InvoiceID int IDENTITY(1,1)PRIMARY KEY CLUSTERED, TableID int ,Amount money)
DECLARE @InvoiceDetail Table(InvoiceID int,FoodID int,Qty int ,orderedDate datetime)

insert into @orderedfood values(1,1,1,'2010/05/21')
insert into @orderedfood values(1,2,3,'2010/05/21')
insert into @orderedfood values(1,3,2,'2010/05/21')
insert into @orderedfood values(2,1,4,'2010/05/21')
insert into @orderedfood values(2,2,2,'2010/05/21')

insert into @Invoices(TableId) SELECT distinct TableId From @OrderedFood

Insert into @InvoiceDetail(InvoiceID,FoodID,Qty,orderedDate)
SELECT InvoiceID,FoodId,Qty,OrderedDate 
FROM @OrderedFood o
inner join @Invoices i on o.tableid = i.tableid

select * from @invoices i inner join @invoicedetail id on i.invoiceid = id.invoiceid


You should use INSER INTO ....SELECT type query for example

INSERT INTO table1 ( column1 )
SELECT  col1
FROM    table2


other one is SELECT INTO Statement

SELECT column_name(s)
INTO new_table_name [IN externaldatabase]
FROM old_tablename
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号