选择前1个字段并分配给局部变量


77

我想从此查询中获取ExtractedDate的值,并在下一个查询中将其用作@LastExtractDate。我怎么做?

    SELECT TOP 1 [ExtractedDate]
    FROM [OnsiteV4].[dbo].[SqlPendingIndex] order by ExtractedDate desc

下一个查询:

    insert into @table(Hex, KeyDeviceId, ObjectDateTime, ExtractedDate  )
SELECT     CONVERT(VARCHAR(MAX), CONVERT(VARBINARY(MAX), ObjectValue, 1)) AS Hex, KeyDeviceId, ObjectDateTime , GETDATE ()
    FROM         SQLPending
    WHERE     (ObjectSubType LIKE '%GAS%') and (ObjectDateTime > @LastExtractDate)

5
这些年来为什么不选择答案哈哈
SketchyTurtle 18-2-22

Answers:



12

只需声明并分配:

DECLARE @LastExtractDate DATETIME = (
    SELECT TOP 1 [ExtractedDate] FROM [OnsiteV4].[dbo].[SqlPendingIndex] order by ExtractedDate desc
)

或更好:

DECLARE @LastExtractDate DATETIME = (
    SELECT MAX(ExtractedDate) FROM [OnsiteV4].[dbo].[SqlPendingIndex]
)

5

简单尝试一下

declare @LastExtractDate date 
SELECT @LastExtractDate=MAX([ExtractedDate])
FROM [OnsiteV4].[dbo].[SqlPendingIndex]

4

用这个:

DECLARE @ExtractedDate DATETIME
SET  @ExtractedDate = (SELECT    TOP 1 ExtractedDate
                       FROM      [OnsiteV4].[dbo].[SqlPendingIndex]
                       ORDER BY  ExtractedDate DESC
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.