如何使用sql语句将一些列从不同的表复制到另一个表中

时间:2011-05-21 16:12:18

标签: sql-server-2005 tsql

我对Sql编码非常紧张。任何解决方案请帮助.... 我有如下表格:

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

我想要复制OrderedFood.TableID => Invoices.TableID。然后复制OrderedFood.FoodID => InvoiceDetail.FoodID,OrderedFood.Qty => InvoiceDetail.Qty这个内容很多行。

我怎么能这样做?

提前致谢...

2 个答案:

答案 0 :(得分:1)

您应该使用INSER INTO ....SELECT类型查询,例如

INSERT INTO table1 ( column1 )
SELECT  col1
FROM    table2


另一个是SELECT INTO陈述

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

答案 1 :(得分:1)

我担心你要确切地想要做什么有点难以理解。 希望以下SQL可以帮助您指明正确的方向

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