IT Share you

Top 1 필드를 선택하고 지역 변수에 할당

shareyou 2020. 12. 15. 20:28
반응형

Top 1 필드를 선택하고 지역 변수에 할당


이 쿼리에서 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)

이것을 사용하지 않는 이유 :

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

간단히 선언 및 할당 :

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

간단히 시도

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

이것을 사용하십시오 :

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

참조 URL : https://stackoverflow.com/questions/24385068/select-top-1-field-and-assign-to-local-variable

반응형