Using Result Set as Variable in Stored Procedure

, 2008-12-08

I’ve been asked several times lately from non-SQL developers that are sometimes required to do some quick SQL work how to use the result set of a query as a variable in a stored procedure. My first thought was I’ll just send them a link to a website that can explain how to do it (yes… so I don’t have to!). After not finding a reference quick enough or maybe basic enough for a non-SQL developer to understand I wrote my own example (also a good excuse for a blog post).

In this example I’m using the AdventureWorksDW2008 database and creating a stored procedure that returns all customer PO numbers where the queried product was sold.

USE AdventureWorksDW2008

ALTER PROC ProductSearch

@ProductName varchar(50)

AS

DECLARE @ProductKey int

SELECT @ProductKey = ProductKey

FROM DimProduct

WHERE EnglishProductName = @ProductName

SELECT CustomerPONumber

FROM FactResellerSales

WHERE ProductKey = @ProductKey

Looking at this query wouldn’t it be easier to just join the two tables? Of course! That’s essentially what’s being done. Like I said though this is more of just an example on how to use a result set in a variable.

Exec ProductSearch 'ML Mountain Frame-W - Silver, 38'

So if your run this procedure here are your results. Hope this helps someone that’s still learning how to work with stored procedures.

CustomerPONumber

1

PO10324111289

2

PO16414129790

3

PO10150121946

4

PO16211136640

5

PO3654183134

Rate

Share

Share

Rate

Related content

Database Mirroring FAQ: Can a 2008 SQL instance be used as the witness for a 2005 database mirroring setup?

Question: Can a 2008 SQL instance be used as the witness for a 2005 database mirroring setup? This question was sent to me via email. My reply follows. Can a 2008 SQL instance be used as the witness for a 2005 database mirroring setup? Databases to be mirrored are currently running on 2005 SQL instances but will be upgraded to 2008 SQL in the near future.

2009-02-23

1,567 reads

Networking - Part 4

You may want to read Part 1 , Part 2 , and Part 3 before continuing. This time around I'd like to talk about social networking. We'll start with social networking. Facebook, MySpace, and Twitter are all good examples of using technology to let...

2009-02-17

1,530 reads

Speaking at Community Events - More Thoughts

Last week I posted Speaking at Community Events - Time to Raise the Bar?, a first cut at talking about to what degree we should require experience for speakers at events like SQLSaturday as well as when it might be appropriate to add additional focus/limitations on the presentations that are accepted. I've got a few more thoughts on the topic this week, and I look forward to your comments.

2009-02-13

360 reads