Solved

Setting a variable in a select statement

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

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

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.
For both online and offline retail, the cross-channel business is the most recent pattern in the B2C trade space.
Using examples as well as descriptions, and references to Books Online, show the documentation available for date manipulation functions and by using a select few of these functions, show how date based data can be manipulated with these functions.
Viewers will learn how to use the UPDATE and DELETE statements to change or remove existing data from their tables. Make a table: Update a specific column given a specific row using the UPDATE statement: Remove a set of values using the DELETE s…

760 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

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now