我有一个oldDB,我想将一个oldDB(tblCustomers
)表拆分为两个newDB表(Customer
和ReservedService
),如下所示:
tblCustomers:(代码,姓名,电话,地址,持续时间,价格)
客户:(身份证,代码,姓名,电话,地址)
ReservedService:(Id,CustomerId,持续时间,价格)
我试过这两个问题:
QUERY1:
use newDB
insert into newDB.dbo.Customer([Code], [Name], [Address], Phone)
select Code, SUBSTRING(Name,1,50), SUBSTRING(Address,1,100), SUBSTRING(Phone,1,50)
from oldDB.dbo.tblCustomers
QUERY2:
use newDB
insert into newDB.dbo.ReservedService(CustomerId, Duration, Price)
select `????`, SUBSTRING(Duration,1,50), SUBSTRING(Price,1,100)
from oldDB.dbo.tblCustomers
请注意,我有两个问题:
CusttomerId
中检索newDB.Customer
并从oldDB.tblCustomers
检索其他字段)如何在没有两个提到的问题的情况下将这两个查询集成到一个查询中?
答案 0 :(得分:2)
@fateme,您可以使用SQL Output clause获取标识值(作为Customer表Id列值),然后将其用于ReservedService表,如下所示
declare @t table (
customerid int, code varchar(10)
)
insert into Customer (
Code, Name, Phone, Address
)
output
inserted.id, inserted.code
into @t(customerid, code)
select Code, Name, Phone, Address
from tblCustomers
insert into ReservedService (
CustomerId, Duration, Price
)
select CustomerId, Duration, Price
from tblCustomers
inner join @t as t
on t.code = tblCustomers.Code
你可以意识到我使用了一个变量表来存储Id和Code关系,以便以后在InsertService的Insert命令中使用
我希望它有所帮助