选择 Top 1字段并赋值给局部变量

我希望从这个查询中获取 ExtratedDate 的值,并在下一个查询中将其作为@LastExtratDate 使用。 我该怎么做?

    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)
109726 次浏览

Simply declare & assign:

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

or better:

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

why not use this:

declare @LastExtractDate date
SELECT TOP 1 @LastExtractDate=[ExtractedDate]
FROM [OnsiteV4].[dbo].[SqlPendingIndex] order by ExtractedDate desc

Use this:

DECLARE @ExtractedDate DATETIME
SET  @ExtractedDate = (SELECT    TOP 1 ExtractedDate
FROM      [OnsiteV4].[dbo].[SqlPendingIndex]
ORDER BY  ExtractedDate DESC

Try this simply

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