Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server SELECT @VARIABLE = TOP 1

I'm trying to perform the following in a stored procedure

DECLARE @TICKET_AGE INT
SELECT @TICKET_AGE = TOP 1 (DATEDIFF(second, DATE_ENTERED, GETDATE())/60) AS TICKET_AGE
FROM TICKETS

But it's giving error saying INCORRECT SYNTAX NEAR 'TOP' What am i doing wrong?

So i've updated my code to look like below...but now am getting Incorrect syntax near the keyword 'AS'.

    -- DECLARE VARIABLE
    DECLARE @TICKET_AGE INT

    -- PULL THE DATA
    SELECT TOP 1 @TICKET_AGE = (DATEDIFF(second, DATE_ENTERED, GETDATE())/60) AS TICKET_AGE
    FROM TICKETS
    WHERE LOWER(STATUS_DESCRIPTION) LIKE '%new%'
    ORDER BY DATE_ENTERED ASC
like image 379
Phil Avatar asked May 04 '16 17:05

Phil


People also ask

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

How do you select the top 2 maximum value in SQL?

Select TOP 2 * from Products where Price = (Select Max(Price) from Products);

How do you select top 10 values in SQL?

Example - Using TOP PERCENT keywordSELECT TOP(10) PERCENT contact_id, last_name, first_name FROM contacts WHERE last_name = 'Anderson' ORDER BY contact_id; This SQL SELECT TOP example would select the first 10% of the records from the full result set.


1 Answers

The TOP 1 comes before the variable:

SELECT TOP 1 @TICKET_AGE = DATEDIFF(second, DATE_ENTERED, GETDATE()) / 60
FROM TICKETS
like image 83
juergen d Avatar answered Nov 01 '22 06:11

juergen d