简体   繁体   English

如何选择比插入列更多的列

[英]How to select more columns than insert column

I have the following query:我有以下查询:

INSERT INTO TableA (Col1, Col2, Col3)
OUTPUT @SomeData, INSERTED.ID, ID INTO TableB(SomeColumn, TableAID, ID)
SELECT Col1, Col2, Col3, ID
FROM TableC;

When I run it, I get this error:当我运行它时,我收到此错误:

The select list for the INSERT statement contains more items than the insert list. INSERT 语句的选择列表包含比插入列表更多的项目。 The number of SELECT values must match the number of INSERT columns. SELECT 值的数量必须与 INSERT 列的数量匹配。

That error makes sense, but I don't know how to fix it.这个错误是有道理的,但我不知道如何解决它。 I want to select 4 columns from TableC , but I want to only insert three of them (Col1, Col2, Col3) into TableA .我想从TableC选择 4 列,但我只想将其中的三个(Col1、Col2、Col3)插入到TableA I am selecting the column ID because I want to insert it into the ID column of TableB .我选择列ID是因为我想将它插入到TableBID列中。 Is there any way to do that?有没有办法做到这一点?

CREATE TABLE TableA
(
    ID bigint identity
        constraint PK_TableA_ID
            primary key
    Col1 int,
    Col2 int,
    Col3 int
)

CREATE TABLE TableB
(
    ID          [int]                NOT NULL,
    SomeColumn  [int]                NOT NULL,
    TableAID    [bigint]             NOT NULL
);

CREATE TABLE TableC
(
    ID          [int] IDENTITY (1,1) NOT NULL,
    Col1        [int],
    Col2        [int],
    Col3        [int],

);

You can try merge and write something like this:您可以尝试合并并编写如下内容:

MERGE TableA AS target
USING TableC AS source 
ON 1 = 0
WHEN NOT MATCHED BY target
THEN INSERT (Col1, Col2, Col3) VALUES (source.Col1, source.Col2, source.Col3)
OUTPUT @SomeData, INSERTED.ID, source.ID INTO TableB (SomeColumn,TableAID, ID);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM