Solved

Setting a variable in a select statement

Posted on 2011-09-27
2
277 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

On Demand Webinar: Networking for the Cloud Era

Ready to improve network connectivity? Watch this webinar to learn how SD-WANs and a one-click instant connect tool can boost provisions, deployment, and management of your cloud connection.

Question has a verified solution.

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

Why is this different from all of the other step by step guides?  Because I make a living as a DBA and not as a writer and I lived through this experience. Defining the name: When I talk to people they say different names on this subject stuff l…
This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
Via a live example, show how to extract insert data into a SQL Server database table using the Import/Export option and Bulk Insert.
Via a live example, show how to shrink a transaction log file down to a reasonable size.

623 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