I'm currently working on a stored procedure in T-SQL on SQL Server 2012. I need to merge 2 tables without an Id. The Id will be created on the insert into the first table. My problem is kind of tricky, thus maybe you can help me :)
In the stored procedure, the import table looks the following way:
CREATE TYPE [MySchema].[Target] AS TABLE
(
IsPrivate BIT,
IsPublic BIT,
CountryId VARCHAR(100)
);
GO
@TARGETS MySchema.Target READONLY
Some possible values for the import @Targets
:
IsPrivate | IsPublic | CountryId |
----------+----------+-------------+
1 | 0 | CA,FR |
0 | 1 | US,GB |
Desired output: these @Targets
I need to split up into 2 tables, Target
and Country
:
Create new entries in
Target
:TargetId | IsPrivate | IsPublic | ---------+-----------+----------+ 23 | 1 | 1 | 24 | 0 | 0 |
Split up the
CountryId
into it's own table,Country
and add theTargetId
:Id | TargetId | CountryId | ---+----------+-----------+ 1 | 23 | CA | 2 | 23 | FR | 3 | 24 | US | 4 | 24 | GB |
My current query looks like this:
CREATE TABLE #tmpTarget (TargetId INT, CountryId VARCHAR(100));
INSERT INTO [MySchema].[Target]([IsPrivate], [IsPublic])
OUTPUT inserted.TargetId, CountryId INTO #tmpTarget
SELECT IsPrivate, IsPublic
FROM @TARGETS
Of course this query doesn't work. I'm currently thinking of how to solve this issue. Do you have some ideas or useful tips for me on how to solve this problem?
Thanks a lot! :)