I have two tables, the structure of the first partially recapitulates, iterates the structure of the second:
table1 (id, i, j, k, a, b, c, x, y, z) -- requests
table2 (id, a, b, c, d) -- essential elements / bank subjects
I need to insert into table1 a record from table2 with given ID.
What is the best approach to do that?
I have two ideas:
1:
DECLARE @a type, @b type, @c type
SELECT @a = a, @b = b, @c = c, FROM table2 WHERE id = @id
INSERT INTO table1 (i, j, k, a, b, c, x, y, z)
VALUES (@i, @j, @k, @a, @b, @c, @x, @y, @z)
2:
CREATE TABLE #result (a type, b type, c type)
SELECT a, b, c INTO #result FROM table2 WHERE id = @id
INSERT INTO table1 (i, j, k, a, b, c, x, y, z)
VALUES (@i, @j, @k,
(SELECT a FROM #result),
(SELECT b FROM #result),
(SELECT c FROM #result),
@x, @y, @z)
What another approach does exists? Which one is the best-practice?
I would do it like this:
This saves you from getting the data in to local variables and/or temp tables. The performance should be better.
The important part to realize is that you can hard code values in the select. The order in which you list the columns (insert line) must match the order in which you list the columns in the select line.