I have the following tables
-- Create the #product table
CREATE TABLE #product
(
id UNIQUEIDENTIFIER PRIMARY KEY DEFAULT NEWID(),
name VARCHAR(100),
createdDate DATE
);
-- Create the #tmpproducts table
CREATE TABLE #tmpProducts
(
rownum INT PRIMARY KEY IDENTITY(1,1),
name VARCHAR(100),
createdDate DATE
);
-- Insert data into #tmpSignings
INSERT INTO #tmpProducts (name, createdDate)
VALUES
('John Doe', '2023-11-22'),
('Jane Smith', '2023-11-23'),
('Alice Johnson', '2023-11-24'),
('Bob Williams', '2023-11-25'),
('Eva Brown', '2023-11-26'),
('Michael Davis', '2023-11-27'),
('Sophia Miller', '2023-11-28'),
('William Wilson', '2023-11-29'),
('Olivia Jones', '2023-11-30'),
('Daniel White', '2023-12-01');
I have 10 rows in #tmpProducts and my objective is to insert these rows into the #product table. For each row successfully inserted into the product table, I need to associate the newly generated ID back to the corresponding rownum in the #tmpProducts table. How can I accomplish this? Any help is greatly appreciated. Thank you!
Expected Output:
Best Answer
Like this:
outputs
You have to use MERGE instead of INSERT as INSERT only allows you to OUTPUT columns from the target table. This is the pattern Entity Framework uses for batch inserts, and Brent Ozar has a blog post on it here.