简体   繁体   English

INSERT INTO with SELECT 使用 OUTPUT

[英]INSERT INTO with SELECT using OUTPUT

I want to store the pt_id into my temporary table by using OUTPUT , however I'm not inserting pt_id into ct_tarf , what should I do?我想使用OUTPUTpt_id存储到我的临时表中,但是我没有将pt_id插入到ct_tarf中,我该怎么办?

I get the following error:我收到以下错误:

The multi-part identifier 'pt_id' could not be bound.无法绑定多部分标识符“pt_id”。

Query:询问:

DECLARE @tbl_ids_tarf TABLE (pt_id INT, pt_id_tarf INT)

INSERT INTO dbo.ct_tarf(tr_id_serv, tr_name, tr_money)
OUTPUT pt_id, inserted.tr_id INTO @tbl_ids_tarf(ptr_id, ptr_id_tarf)
   SELECT 
      pt_id_serv, pt_name, pt_money
   FROM 
      dbo.opr_prop_tar
   WHERE 
      pt_id_tarf

SQL2008+: SQL2008+:

Assuming that you want to insert into @tbl_ids_tarf (which is target of OUTPUT ... INTO clause) values from columns that are not returned by inserted or deleted virtual tables then one solution is to use MERGE statement instead of INSERT :假设您要从inserteddeleted的虚拟表未返回的列中插入@tbl_ids_tarf (这是OUTPUT ... INTO子句的目标)值,那么一种解决方案是使用MERGE 语句而不是INSERT

DECLARE @Target TABLE (
    Col1 INT
)
INSERT  @Target VALUES (1), (2);

DECLARE @Output TABLE (Col1 INT, ColB INT);

;WITH Source
AS (
    SELECT  * 
    FROM    (VALUES (10, 100), (20, 200), (30, 300)) x(ColA, ColB)
)
MERGE INTO @Target x
USING Source y ON x.Col1 = y.ColA
WHEN NOT MATCHED BY TARGET THEN 
    INSERT (Col1) VALUES (y.ColA)
OUTPUT inserted.Col1, y.ColB INTO @Output (Col1, ColB); 
--                     ^-- y.ColB isn't returned by inserted or deleted virtual tables. 
-- inserted and deleted are based on `@Target` table [variable]

SELECT * FROM @Output;
/*
Col1        ColB
----------- -----------
10          100
20          200
30          300
*/

You have several issues with your query - column naming is one, an incomplete WHERE clause is another, and a missing Inserted.您的查询有几个问题 - 列命名是一个,不完整的WHERE子句是另一个,并且缺少Inserted. prefix is the third.前缀是第三个。

Try this:尝试这个:

DECLARE @tbl_ids_tarf TABLE (pt_id INT, pt_id_tarf INT)

INSERT INTO dbo.ct_tarf(tr_id_serv, tr_name, tr_money)
OUTPUT inserted.pt_id, inserted.tr_id INTO @tbl_ids_tarf(pt_id, pt_id_tarf)
--     *********                                         ******************
   SELECT 
      pt_id_serv, pt_name, pt_money
   FROM 
      dbo.opr_prop_tar
   WHERE 
      pt_id_tarf --........

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

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