I have 2 tables like:
ID NAME
-------------
1 someValue
2 someValue
3 someValue
4 someValue
...
ID NAME
-------------
1 var
2 var2
3 var3
4 var4
...
I want to insert in a @table
2 results from table1, and, 3 results from table2, with different ID, Currently I have something like:
Declare @vars TABLE(
field1 varchar(80),
field2 varchar(80),
field3 varchar(80),
field4 varchar(80),
field5 varchar(80)
)
INSERT INTO @vars(field1, field2, field3, field4, field5)
SELECT a.Name,
b.Name,
c.Name,
d.Name,
e.Name
FROM @Table1 a,
@Table1 b,
@Table2 c,
@Table2 d,
@Table2 e
WHERE a.ID = 1
AND b.ID = 25
AND c.ID = 12
AND d.ID = 25开发者_C百科
AND e.ID = 14
I get the expected values, but...
- Is there a more elegant way to do this? I guess I´m doing more than needed.
P.D. I get something like:
field1 field2 field3 field4 field5
-------------------------------------
val1 var2 val4 val7 var7
If ID is a primary key or unique key in Table1 and Table 2 you can do this instead.
insert into @vars
select
(select Name from @Table1 where ID = 1),
(select Name from @Table1 where ID = 25),
(select Name from @Table2 where ID = 12),
(select Name from @Table2 where ID = 25),
(select Name from @Table2 where ID = 14)
I'm not sure if it's more elegant, but here's a different query that does the same.
WITH myTables AS
( SELECT ID, NAME, 'Table1' AS SOURCE
FROM Table1
UNION ALL
SELECT ID, NAME, 'Table2' AS SOURCE
FROM Table2
)
INSERT INTO @vars(field1, field2, field3, field4, field5)
SELECT MAX(CASE WHEN source = 'Table1' AND id = 1 THEN NAME END) AS field1,
MAX(CASE WHEN source = 'Table1' AND id = 25 THEN NAME END) AS field2,
MAX(CASE WHEN source = 'Table2' AND id = 12 THEN NAME END) AS field3,
MAX(CASE WHEN source = 'Table2' AND id = 25 THEN NAME END) AS field4,
MAX(CASE WHEN source = 'Table2' AND id = 14 THEN NAME END) AS field5
FROM myTables
WHERE SOURCE = ('Table1' AND ID IN (1, 25))
OR (SOURCE = 'Table2' AND ID IN (12, 25, 14)) ;
It uses a common table expression (CTE) to create a union of the two tables. It also pivots the data using the MAX aggregation. You can also do this with the PIVOT operator.
精彩评论