I'm working on a stored procedure in TSQL on SQL Server 2012. When I call the stored procedure. My problem: I'm inserting the values into a table Projects
and want to store the inserted.ProjectId
together with oID
from the importing table into a temporary Table; I don't store the oID
from the importing table into the Projects
table.
I'm referring myself to this answer: Insert Into... Merge... Select (SQL Server)
1) Importing Table: I'm sending a table from C# to SQL with the following values:
oID | Title |
----+----------+
0 | ProjectX |
1 | ProjectY |
2 | ProjectZ |
It looks like this in the stored procedure:
CREATE TYPE [MySchema].[Project] AS TABLE
(
oID INT,
Title VARCHAR(100)
);
@ImportProjects MySchema.Project READONLY
2) Projects Table: I'm inserting the values into the Table Projects, and want to store the inserted.ProjectId as well as the oID from the importing Table into a temporary table:
ProjectId | Title |
----------+----------+
33 | ProjectX |
34 | ProjectY |
35 | ProjectZ |
3) Desired Output, Temporary Table: In my temporary table I want to store the ProjectId as well as the oID from the importing table:
RowID | oID | ProjectId |
--------+-----+--------------+
1 | 0 | 33 |
2 | 1 | 34 |
3 | 2 | 35 |
My Merge query looks like this:
create table Temp (ProjectId INT, oID INT)
MERGE INTO Temp USING
(
SELECT
a.oID as oID,
b.ProjectId as ProjectId
FROM @ImportProjects a
CROSS JOIN Projects b
) AS s ON 1 = 0
WHEN NOT MATCHED THEN
INSERT (oID, ProjectId)
VALUES (s.oID, s.ProjectId)
OUTPUT Inserted.ProjectId, s.oID
INTO Temp(oID, ProjectId);
This doesn't really work... One of my problems is of course the cross join, but i dont have a link or foreign key inbetween importing table and projects table...
Do you know how to achieve this?
Thank you !! :)