SQL 选择 Top 1 字段并分配给局部变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24385068/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 02:06:32  来源:igfitidea点击:

Select Top 1 field and assign to local variable

sqlsql-server

提问by Steve Staple

I want to take the value of ExtractedDate from this query and use it as @LastExtractDate in the next query. How do I do that?

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

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

next query:

下一个查询:

    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)

回答by Brett Schneider

why not use this:

为什么不使用这个:

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

回答by Alex K.

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]
)

回答by Jesuraja

Use this:

用这个:

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

回答by KrushnaKPawar

Try this simply

简单地试试这个

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