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?
I get the following error:
The multi-part identifier 'pt_id' could not be bound.
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
You can use a select-statement within an INSERT statement to insert zero, one, or more rows into a table from the result table of the select-statement. The select-statement embedded in the INSERT statement is no different from the select-statement you use to retrieve data.
You can still insert records into the destination table with specifying column names in the INSERT INTO SELECT statement.
You can return any of the columns of the table you're inserted a row into, in your OUTPUT clause. So even if you don't provide a value for a given column in your INSERT statement, you can still specify that column in the OUTPUT clause. You can however not return SQL variables or columns from other tables.
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
:
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
*/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With