获取最后插入的值和if语句mssql

时间:2014-03-26 11:40:05

标签: sql-server tsql

我有这个数据库设置:http://sqlfiddle.com/#!6/3076a/4

编辑:

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

tablename应该是可变的,这是我为它创建存储过程的原因

1 个答案:

答案 0 :(得分:0)

我猜你可以在NOT EXIST语句中使用INSERT条件来测试行的存在。

IF NOT EXISTS ( [subquery] ) INSERT INTO ... VALUES(...)

NOT EXIST的文件在这里: http://technet.microsoft.com/en-us/library/ms188336.aspx


要指定具有最大SensorTime的行,您可以使用MAX( )函数,如下所示:

MAX(SensorTime) = SensorTime

这意味着maxmum值等于该行的值。

MAX( )功能的文件在这里: http://technet.microsoft.com/en-us/library/ms187751.aspx


所以,你的代码可能是这样的:

IF NOT EXISTS (
  SELECT *  FROM Sensor1 WHERE SensorTime <= @date 
  AND SensorTime = MAX(SensorTime) AND SensorValue = @value
) 
INSERT INTO Sensor1 (SensorTime, SensorValue) VALUES (@date, @value)

希望这有帮助。