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
Solved

Setting a variable in a select statement

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

The Eight Noble Truths of Backup and Recovery

How can IT departments tackle the challenges of a Big Data world? This white paper provides a roadmap to success and helps companies ensure that all their data is safe and secure, no matter if it resides on-premise with physical or virtual machines or in the cloud.

Question has a verified solution.

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

This article shows gives you an overview on SQL Server 2016 row level security. You will also get to know the usages of row-level-security and how it works
In this article we will learn how to fix  “Cannot install SQL Server 2014 Service Pack 2: Unable to install windows installer msi file” error ?
Familiarize people with the process of retrieving data from SQL Server using an Access pass-thru query. Microsoft Access is a very powerful client/server development tool. One of the ways that you can retrieve data from a SQL Server is by using a pa…
Viewers will learn how to use the SELECT statement in SQL to return specific rows and columns, with various degrees of sorting and limits in place.

856 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