我有以下SQL尝试使用子查询插入financial_history_details表,因为我需要语句从表的其他部分提取数据。
如果有一行信息,这是可以的。我的问题是我试图插入数千行数据,从不同的表中提取某些信息(batch_number, contact_number
)。
我考虑过使用子语句,如本声明中所示,但我已经说过它不能很好地工作,因为它一次只插入一个数据。
INSERT INTO financial_history (batch_number, transaction_number, contact_number, transaction_date,
transaction_type, amount, payment_method, posted, address_number, currency_amount)
VALUES ((select batch_number from event_bookings where batch_number not in (select batch_number from batches)), 1,
(select contact_number from event_bookings where batch_number not in (select batch_number from batches)),
'20-sep-2017', 'P', 0, 'CASH', '20-sep-2017',
(select address_number from event_bookings where batch_number not in (select batch_number from batches)), 0) ;
我也尝试过使用CSV导入,但这会导致许多问题,使其成为不切实际的解决方案:
BULK
INSERT batches
FROM 'C:\batches.csv'
WITH
(
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n'
)
GO
还有其他方法吗?
答案 0 :(得分:1)
您似乎想要insert . . . select
:
insert into financial_history (batch_number, transaction_number, contact_number, transaction_date,
transaction_type, amount, payment_method, posted, address_number, currency_amount)
select . . .
from event_bookings
where batch_number not in (select batch_number from batches);
目前还不清楚您希望列的值是什么。
答案 1 :(得分:0)
您可以使用单个SELECT并避免重复多次访问同一个表(您也可以使用SELECT而不使用insert来检查输出)
INSERT INTO financial_history (batch_number, transaction_number, contact_number, transaction_date,
transaction_type, amount, payment_method, posted, address_number, currency_amount)
SELECT batch_number, 1, contact_number, '20-sep-2017', 'P', 0, 'CASH', '20-sep-2017', address_number from event_bookings
WHERE batch_number not in (select batch_number from batches);
提示:
同一查询的更易读的形式:
INSERT INTO financial_history (batch_number, transaction_number, contact_number, transaction_date,
transaction_type, amount, payment_method, posted, address_number, currency_amount)
SELECT batch_number
, 1 AS TRANSACTION_NUMBER
, contact_number
, '20-sep-2017' AS TRANSACTION_DATE
, 'P' AS TRANSACTION TYPE
, 0 AS AMOUNT
, 'CASH' AS PAYMENT_METHOD
, '20-sep-2017' AS POSTED
, address_number
FROM event_bookings
WHERE batch_number not in (select batch_number from batches);