我想使用pt_id
将OUTPUT
存储到我的临时表中,但是我没有将pt_id
插入ct_tarf
,我该怎么办?
我收到以下错误:
多部分标识符' pt_id'无法受约束。
查询:
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
答案 0 :(得分:8)
<强> SQL2008 +:强>
假设您要从@tbl_ids_tarf
或OUTPUT ... INTO
个虚拟表未返回的列中插入inserted
(deleted
子句的目标)值,则解决方案是使用MERGE statement代替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
*/
答案 1 :(得分:7)
您的查询有几个问题 - 列命名是一个,不完整的WHERE
子句是另一个,缺少Inserted.
前缀是第三个。
试试这个:
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 ........