我需要帮助才能做到这一点:
TABLE POSITION
ID, int (PK)
SN, varchar(10)
Lat, double
Lon, double
etc...
TABLE ACTUAL_POSITION
SN, varchar(10) (PK)
Lat, double
Lon, double
当在第一个表中插入记录时,应在第二个表中更新相应的(通过SN)记录。如果在该表中没有找到SN记录,则应该创建它。
多个记录同时插入第一个表中,即使是相同的SN,所以我需要为每个SN提取最后一个Lat和Lon(当车辆超出连接范围时,它们将数据缓冲到发送然后将其全部发送到togheter,以便接收sw从插入的表中一次性写入sql。
答案 0 :(得分:2)
CREATE TRIGGER dbo.SummarizePosition
ON dbo.Position
FOR INSERT
AS
BEGIN
;WITH x AS
(
SELECT SN, Lat, Long,
rn = ROW_NUMBER() OVER (PARTITION BY SN
ORDER BY ID DESC) -- or by timestamp col desc
FROM inserted
WHERE EXISTS
( SELECT 1 FROM dbo.Actual_Position AS p
WHERE p.SN = inserted.SN
)
)
UPDATE p
SET p.Lat = x.Lat,
p.Lon = x.Lon
FROM dbo.Actual_Position AS p
INNER JOIN x ON x.sn = p.sn
WHERE x.rn = 1;
;WITH x AS
(
SELECT SN, Lat, Long, /* other cols, */
rn = ROW_NUMBER() OVER (PARTITION BY SN
ORDER BY ID DESC) -- or by timestamp col desc
FROM inserted
WHERE NOT EXISTS
( SELECT 1 FROM dbo.Actual_Position AS p
WHERE p.SN = inserted.SN
)
)
INSERT dbo.Actual_Position(SN, Lat, Long /*, other cols */)
SELECT SN, Lat, Lon /*, other cols */
FROM x
WHERE rn = 1;
END
GO
答案 1 :(得分:0)
每次在POSITION中插入新行时,您都可以创建一个触发器来更新ACTUAL_POSITION。
有关SQL Server 2005中触发器的更多信息,请参阅this MSDN article。