使用SQL中的表数据填充声明的变量

时间:2015-05-13 15:14:19

标签: sql-server tsql

我正在尝试从数据库中的小时表中获取值。我需要机器名称,总小时数和从4周前记录的日期(我正在创建时不使用日期时间功能,因为我不能保证我正在建造的仪表将在正确的日子读取)我有一个汇总功能来显示自那以后的日子1/1/1 0:00:00(或类似的东西)所以我试图用这个:

Declare @Value as Integer

WITH Derp as (Select top 4 [HLRD], TotalHours, MachineName from dbo.HourMeterLog where MachineName = 'Chester' ORDER BY HLRD Desc)
 @Value = MIN(Derp.HLRD)

WITH Derp as (Select top 4 [HLRD], TotalHours, MachineName from dbo.HourMeterLog where MachineName = 'Chester' ORDER BY HLRD Desc)
Select * from Derp where HLRD = @Value

但我似乎无法让@Value接受我需要的价值。任何人都能告诉我我做错了什么或者建议我找到更好的答案吗?

1 个答案:

答案 0 :(得分:2)

这将是您想要的正确语法:

DECLARE @Value INT;

WITH Derp AS 
(
    SELECT TOP 4 [HLRD], 
                 TotalHours, 
                 MachineName 
    FROM dbo.HourMeterLog 
    WHERE MachineName = 'Chester' 
    ORDER BY HLRD DESC
)
SELECT @Value = MIN(HLRD)
FROM Derp;

WITH Derp AS 
(
    SELECT TOP 4 [HLRD], 
                 TotalHours, 
                 MachineName 
    FROM dbo.HourMeterLog 
    WHERE MachineName = 'Chester' 
    ORDER BY HLRD DESC
)
SELECT * 
FROM Derp 
WHERE HLRD = @Value;

当然,这可以更简单地完成:

WITH CTE AS
(
    SELECT  *,
            ROW_NUMBER() OVER(ORDER BY HLRD DESC) RN
    FROM dbo.HourMeterLog 
    WHERE MachineName = 'Chester' 
)
SELECT *
FROM CTE
WHERE RN = 4;