99

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?

    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)
Jesuraja
  • 3,774
  • 4
  • 24
  • 48
Steve Staple
  • 2,983
  • 9
  • 38
  • 73

4 Answers4

158

why not use this:

declare @LastExtractDate date
SELECT TOP 1 @LastExtractDate=[ExtractedDate]
FROM [OnsiteV4].[dbo].[SqlPendingIndex] order by ExtractedDate desc
podiluska
  • 50,950
  • 7
  • 98
  • 104
Brett Schneider
  • 3,993
  • 2
  • 16
  • 33
  • 2
    This syntax is not correct. You will get NULL value in Sql Server if you try to run this code. You need to assign the value to the variable from a subquery. Example: `declare @SomeVar varchar(100) = (select top 1 someCol from someTable)` – HamsterWithPitchfork Oct 25 '22 at 13:33
24

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]
)
Alex K.
  • 171,639
  • 30
  • 264
  • 288
9

Use this:

DECLARE @ExtractedDate DATETIME
SET  @ExtractedDate = (SELECT    TOP 1 ExtractedDate
                       FROM      [OnsiteV4].[dbo].[SqlPendingIndex]
                       ORDER BY  ExtractedDate DESC
Jesuraja
  • 3,774
  • 4
  • 24
  • 48
5

Try this simply

declare @LastExtractDate date 
SELECT @LastExtractDate=MAX([ExtractedDate])
FROM [OnsiteV4].[dbo].[SqlPendingIndex]
Andy
  • 49,085
  • 60
  • 166
  • 233