子查询在插入中返回多个结果

Sub query returning multiple results within an insert

我有下面的 SQL,它试图使用子查询插入到 financial_history_details table 中,因为我需要语句从 [=25] 的其他部分提取数据=].

只有一行信息就可以了。我的问题是我试图插入数千行数据,其中某些信息 (batch_number, contact_number) 从不同的 table 中提取。

我考虑过使用此语句中所示的子查询,但正如我已经说过的那样,它的效果并不理想,因为它一次只能插入一条数据。

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

还有其他方法吗?

你似乎想要一个 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);

虽然不清楚您希望列的值是什么。

您可以使用,使用单个 SELECT 并避免重复多次访问相同的 table(您也可以使用 SELECT 而不插入来检查输出)

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);

提示:

  • 对日期使用 CONVERT,不要依赖隐式转换(假设您的目标列是日期时间数据类型:例如 CONVERT(datetime,'20/09/2017', 103) 106))

同一查询的可读性更高的形式:

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);