【问题标题】:Sub query returning multiple results within an insert子查询在插入中返回多个结果
【发布时间】:2017-09-28 13:51:07
【问题描述】:

我有下面的 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

还有其他方法可以做到这一点吗?

【问题讨论】:

    标签: sql sql-server-2016


    【解决方案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);
    

    不过,尚不清楚您希望列的值是什么。

    【讨论】:

      【解决方案2】:

      您可以使用,使用单个 SELECT 并避免对同一个表重复多次访问(您也可以使用不插入的 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);
      

      【讨论】:

        猜你喜欢
        • 2023-04-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-12
        • 2021-03-25
        • 2010-09-25
        • 2020-10-23
        相关资源
        最近更新 更多