我有两个表,一个是sensor_pool
,它是更改temp_cel
值和计时器间隔
sensor_pool
| 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 |
希望有人可以帮助我
谢谢
答案 0 :(得分: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')