假设我有两个表FOO和BAR如下所示,如果您根据BAR表的连接知道列名为字符串,是否可以在FOO上使用某种反射?
SELECT DB, FOO.Name, FOO.Type, BAR.Field, I.DATA_TYPE AS FType, FOO.**<BAR.FIELD>** AS Value
FROM INFORMATION_SCHEMA.COLUMNS AS I
inner JOIN BAR ON I.COLUMN_NAME = BAR.Field
inner JOIN FOO ON FOO.TYPE = BAR.TYPE
WHERE DB = 4 AND FLAG = 1
即。对于每个选定的行,FOO。 需要更改以反映FOO中匹配列的值,即如果一行具有BAR {4,AC1,LO}和FOO {4,AC1,LO, COL1}我希望选择值1。
我知道我可以做到这一点是2轮并且合并数据,但是我想知道是否有人知道如何在1转中更有效地做到这一点,节省代码路径。
我应该补充一下,我通常在任一个表中有大约60列,它们非常随机,即我不能假设col1,2或3存在,我只能通过等效BAR表中的内容。< / p>
FOO:
+--------+--------+---------+---------+--------+-------+
| DB | Name | Type | Col1 | Col2 | Col3 |
+--------+--------+---------+---------+--------+-------+
| 4 | AC1 | LO | 1 | 10 | 2 |
| 4 | AC1 | HI | 2 | 20 | 4 |
| 1 | DC2 | HI-HI | 11 | 5 | 2 |
| 1 | DC2 | HI | 22 | 10 | 4 |
| 1 | DC2 | LO | 33 | 15 | 6 |
+--------+--------+---------+---------+--------+-------+
BAR:
+--------+--------+---------+---------+--------+
| DB | Name | Type | Field | Flag |
+--------+--------+---------+---------+--------+
| 4 | AC1 | LO | Col1 | 1 |
| 4 | AC1 | HI | Col1 | 1 |
| 1 | DC2 | HI-HI | Col1 | 1 |
| 1 | DC2 | HI | Col1 | 1 |
| 1 | DC2 | LO | Col1 | 1 |
| 4 | AC1 | LO | Col2 | 0 |
| 4 | AC1 | HI | Col2 | 0 |
| 1 | DC2 | LO | Col2 | 0 |
| 1 | DC2 | HI-HI | Col2 | 0 |
| 1 | DC2 | HI | Col2 | 0 |
| 4 | AC1 | LO | Col3 | 0 |
| 4 | AC1 | HI | Col3 | 0 |
| 1 | DC2 | LO | Col3 | 0 |
| 1 | DC2 | HI-HI | Col3 | 0 |
| 1 | DC2 | HI | Col3 | 0 |
+--------+--------+---------+---------+--------+
结果:
+--------+--------+---------+---------+--------+--------+
| DB | Name | Type | Field | FTYPE | VALUE |
+--------+--------+---------+---------+--------+--------+
| 4 | AC1 | LO | Col1 | float | 1 |
| 4 | AC1 | HI | Col1 | float | 2 |
| 4 | AC1 | LO | Col2 | float | 10 |
| 4 | AC1 | HI | Col2 | float | 20 |
| 4 | AC1 | LO | Col3 | float | 2 |
| 4 | AC1 | HI | Col3 | float | 4 |
+--------+--------+---------+---------+--------+--------+