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 2005 Forums
 Transact-SQL (2005)
 Select only 1 value

Author  Topic 

Heinz23
Yak Posting Veteran

84 Posts

Posted - 2008-12-30 : 12:03:44
Hi all,
ok, I could use TOP 1 to get only 1 row back, but this does not seem to work when I want to store the result in a variable, or I'm using a wrong syntax.

So I have a select like: SELECT PostedDate From POSTS Where UserID = 1 ORDER BY PostedDate DESC
How could I store it in a variable? Like: SET @LastPost = PostedDate From POSTS Where UserID = 1 ORDER By PostedDate DESC ?
I've seen that I could use 'ORDER BY PostedDate ASC' and then I get the last value, probably because the SELECT is continously overwriting its result? However, I guess this is not the best solution so maybe someone could give me a short hint?

Many thanks!

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2008-12-30 : 12:15:41
You can put the result of TOP into a variable:

SELECT TOP1 @var1 = Column1
FROM Table1
ORDER BY SomeColumn DESC

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-12-30 : 12:15:49
[code]SELECT TOP 1 @LastPost = PostedDate From POSTS Where UserID = 1 ORDER BY PostedDate DESC[/code]
Go to Top of Page

Heinz23
Yak Posting Veteran

84 Posts

Posted - 2008-12-30 : 13:45:12
Hi Tara, visakh,

thanks a lot, of course this works fine!

Best regards!
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-12-30 : 13:48:45
welcome
Go to Top of Page

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2008-12-30 : 13:49:31
You're welcome.

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page
   

- Advertisement -