Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 SQL Server Development (2000)
 Stored Procedure?

Author  Topic 

tribe
Starting Member

1 Post

Posted - 2002-08-28 : 12:51:17
How in SQL would I select a certain row from the results
of a query.

Example SQL:

Select name from table

Returns:

Bob
Joe
Chad
Tim

How would I set a variable equal to the 3rd row?


nr
SQLTeam MVY

12543 Posts

Posted - 2002-08-28 : 12:56:10
You wouldn't.

select name from table is unordered so the 3rd row doesn't have any meaning until the cursor is created - which is for delivery to the client.
If you have any ordering field you can do it:

select top 1 * from (select top 3 name from tbl order by name) as a order by name desc


==========================================
Cursors are useful if you don't know sql.
DTS can be used in a similar way.
Beer is not cold and it isn't fizzy.
Go to Top of Page

MichaelP
Jedi Yak

2489 Posts

Posted - 2002-08-28 : 12:56:32
DECLARE @FirstName VARCHAR (50)

SELECT @FirstName = name FROM mytable WHERE name='chad'


Seems kinda silly to do since you have to know 'chad' to get 'chad'
I'm guessing you want something like this:

SELECT @FirstName = name FROM mytable WHERE id=3



<Yoda>Use the Search page you must. Find the answer you will.</Yoda>
Go to Top of Page

AjarnMark
SQL Slashing Gunting Master

3246 Posts

Posted - 2002-08-28 : 13:20:13
quote:
Seems kinda silly to do since you have to know 'chad' to get 'chad'
I'm guessing you want something like this:

SELECT @FirstName = name FROM mytable WHERE id=3




Please note that there is nothing magical about the word id in the above code. The above code ASSUMES that you have a field named id and that it is something like and identity field (a.k.a. auto-incrementing) and was assigned that number. As nr mentions, data in SQL Server is not necessarily returned in the same order every time you issue a query unless you specify and ORDER BY statement.

Go to Top of Page
   

- Advertisement -