我有這個數據庫設置:http://sqlfiddle.com/#!6/3076a/4獲得最後插入的值,如果聲明MSSQL
編輯:
CREATE TABLE [dbo].[Sensor1](
[SensorTime] [datetime] NOT NULL,
[SensorValue] [float] NOT NULL,
PRIMARY KEY CLUSTERED
(
[SensorTime] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
INSERT INTO dbo.Sensor1(SensorTime, SensorValue) VALUES ('2014-03-17 11:10:34.343', 10);
INSERT INTO dbo.Sensor1(SensorTime, SensorValue) VALUES ('2014-03-17 11:20:34.343', 20);
INSERT INTO dbo.Sensor1(SensorTime, SensorValue) VALUES ('2014-03-17 11:30:34.343', 30);
CREATE PROCEDURE [dbo].[SelectLatestByDate]
@name nvarchar(128),
@date datetime
AS
DECLARE @sql NVARCHAR(MAX)
SET @sql = N'
SELECT TOP 1 * FROM '+ QUOTENAME(@name) +' WHERE SensorTime <= @date ORDER BY SensorTime DESC
'
EXEC sp_executesql @sql, N'@date datetime', @date = @date
RETURN
現在,每當一個新的值將被插入,我希望做一個檢查,看是否它不等於最後一個值。如果相同,則不應插入值。現在我有這個存儲過程要做到這一點,但它是緩慢的,我想知道如果有一個更快的方法...
CREATE PROCEDURE [dbo].[PutData]
@name nvarchar(128),
@date datetime,
@value float
AS
DECLARE @Table TABLE
(
SensorTime datetime,
SensorValue float
)
INSERT INTO @Table
EXEC dbo.SelectLatestByDate @name, @date
DECLARE @lastValue float
SELECT @lastValue = [@Table].[SensorValue] FROM @Table
IF (@lastValue != @value)
BEGIN
DECLARE @sql NVARCHAR(MAX)
SET @sql = N'
INSERT INTO ' + QUOTENAME(@name) + ' (SensorTime, SensorValue) VALUES (@date, @value)
'
EXEC sp_executesql @sql, N'@date datetime, @value float', @date = @date, @value = @value
END
RETURN 0
的表名應該是可變的,這是我做了一個存儲過程的原因它
你可以顯示'dbo.SelectLatestByDate'的定義嗎? –
在主題 – user3182508