Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select Top 1 field and assign to local variable

Tags:

sql

sql-server

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) 
like image 702
Steve Staple Avatar asked Jun 24 '14 11:06

Steve Staple


People also ask

How do you assign a value from a select statement to a variable in SQL?

When a variable is first declared, its value is set to NULL. To assign a value to a variable, use the SET statement. This is the preferred method of assigning a value to a variable. A variable can also have a value assigned by being referenced in the select list of a SELECT statement.

What does top 1 do in SQL?

The TOP 1 means to only return one record as the result set. which record is returned, depends on the column that is specified in the order by clause. If you want to find the record with the minimum value for a particular column, you would query the record with the ORDER BY being ascending (ASC).

What is the difference between select * and select 1?

Select * from any table will fetch and display all the column in that table, while Select 1 from any table will display one row with 1 without any column name.


2 Answers

why not use this:

declare @LastExtractDate date SELECT TOP 1 @LastExtractDate=[ExtractedDate] FROM [OnsiteV4].[dbo].[SqlPendingIndex] order by ExtractedDate desc 
like image 145
Brett Schneider Avatar answered Sep 21 '22 17:09

Brett Schneider


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] ) 
like image 28
Alex K. Avatar answered Sep 17 '22 17:09

Alex K.