Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Setting a variable in a select statement

Posted on 2011-09-27
2
Medium Priority
?
286 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 93

Accepted Solution

by:
Patrick Matthews earned 2000 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

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

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

Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
It is possible to export the data of a SQL Table in SSMS and generate INSERT statements. It's neatly tucked away in the generate scripts option of a database.
Via a live example, show how to shrink a transaction log file down to a reasonable size.
Viewers will learn how to use the INSERT statement to insert data into their tables. It will also introduce the NULL statement, to show them what happens when no value is giving for any given column.

916 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