Solved

Setting a variable in a select statement

Posted on 2011-09-27
2
274 Views
Last Modified: 2012-06-27
I have the following simple query:

declare @product varchar(50);
select top 1 productid, count(*) as total from orderlines  group by productid order by total desc

I need to get the productid from the query, store it in the variable @product and then use the variable in another query. How can i do that in MS SQL Server 2008?
0
Comment
Question by:troycomp
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
2 Comments
 
LVL 92

Accepted Solution

by:
Patrick Matthews earned 500 total points
ID: 36713050
Something like this:

declare @product varchar(50);
set @product = (select top 1 productid
    from orderlines  
    group by productid 
    order by count(*) desc)

SELECT *
FROM product_orders
WHERE productid = @product

Open in new window

0
 

Author Comment

by:troycomp
ID: 36713057
Thank you!!!
0

Featured Post

Free eBook: Backup on AWS

Everything you need to know about backup and disaster recovery with AWS, for FREE!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Use this article to create a batch file to backup a Microsoft SQL Server database to a Windows folder.  The folder can be on the local hard drive or on a network share.  This batch file will query the SQL server to get the current date & time and wi…
In this article we will get to know that how can we recover deleted data if it happens accidently. We really can recover deleted rows if we know the time when data is deleted by using the transaction log.
This videos aims to give the viewer a basic demonstration of how a user can query current session information by using the SYS_CONTEXT function
Viewers will learn how to use the SELECT statement in SQL and will be exposed to the many uses the SELECT statement has.

710 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question