1

我有两张表,一张是用定时器间隔sensor_pool改变值temp_cel

传感器池

| address | temp_cels |
|---------------------|
| sensor1 | 83C       |
| sensor2 | 82C       |
| sensor3 | 85C       |
| sensor4 | 85C       |
| sensor5 | 84C       |

和另一个sensor_history我动态创建列的表(添加了传感器地址作为列名的列)。我能够捕获日期时间,但不能temp_cels从另一个表中捕获。

INSERT INTO sensor_history(datetime) VALUES(" & dtfStr & ")
  • dtfStr = timestamp

传感器历史

|    datetime    | sensor1 | sensor2 | sensor3 | sensor4 | sensor5 | 
|------------------------------------------------------------------|
| 12022013080513 |  NULL   |  NULL   |  NULL   |  NULL   |  NULL   |

到目前为止,我有一个在 for 循环内的查询(用于获取列)

IF EXISTS(SELECT datetime FROM sensor_history where datetime='" & dtfStr & "') 
MERGE sensor_history sh USING sensor_pool sp ON [(SELECT '" & dgvSensors.Rows(l).Cells(0).Value & "' 
FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='sensor_history' AND COLUMN_NAME='" & dgvSensors.Rows(l).Cells(0).Value & "')] = sp.sens_code 
WHEN MATCHED THEN UPDATE SET sh.[" & dgvSensors.Rows(l).Cells(0).Value & "] = st.temp_cels 
WHEN NOT MATCHED BY TARGET THEN INSERT ([" & dgvSensors.Rows(l).Cells(0).Value & "]) VALUES (st.temp_cels);"

dgvSensors datagridview 与 sensor_pool 表相同。vb.net + SQL Server

这就是我的目标结果应该是:

|    datetime    | sensor1 | sensor2 | sensor3 | sensor4 | sensor5 | 
|------------------------------------------------------------------|
| 12022013080513 |   83C   |   82C   |   85C   |   85C   |   84C   |

希望有人能帮助我

谢谢你

4

1 回答 1

0
INSERT INTO sensor_history(datetime,sensor1,sensor2,sensor3,sensor4,sensor5) 
VALUES(getdate(),
select temp_cels from sensor_pool where address='sensor1',
select temp_cels from sensor_pool where address='sensor2',
select temp_cels from sensor_pool where address='sensor3',
select temp_cels from sensor_pool where address='sensor4',
select temp_cels from sensor_pool where address='sensor5')
于 2013-02-12T06:00:39.370 回答