tags:

views:

88

answers:

3

Hi there, I am trying to write a sql statement that

I have 2 tables Store & StoreTransactions. My first select command looks like

SELECT [StoreID],[ParentStoreID] 
FROM Store

Very simple stuff. How do I take the returned StoreID's and use them for my 2nd select statement?

SELECT [StoreTransactionID],[TransactionDate],[StoreID]
FROM StoreTransactions
WHERE StoreID = returned values from the above query

Any help would be great!

+3  A: 
SELECT [StoreTransactionID],[TransactionDate],[StoreID]
FROM StoreTransactions
WHERE StoreID in (select StoreId from Store)

This is known as a nested select, or inner select.

Joel Potter
Hi Joel,I get an error Msg 116, Level 16, State 1, Line 16Only one expression can be specified in the select list when the subquery is not introduced with EXISTS. I will look further into nested selects.Thank you
RE: Your error You must have changed this part to have more than one column? *select StoreId from Store* or are using = instead of in?
Martin Smith
@diver, When using in, your nested select must return an array like set (i.e. one column). Notice the sql I wrote only has one field in the nested select.
Joel Potter
+1  A: 

Couple of other ways of doing it...

SELECT [StoreTransactionID],[TransactionDate],[StoreID]
FROM StoreTransactions st
WHERE EXISTS
(
SELECT * 
FROM Store s
WHERE s.[StoreID] = st.[StoreID]
)

And

SELECT [StoreTransactionID],[TransactionDate],st.[StoreID]
FROM StoreTransactions st
INNER JOIN Store s ON s.[StoreID] = st.[StoreID]
Martin Smith
Both good suggestions. Personally I prefer an inner join to a nested select.
Joel Potter
+1  A: 

An alternative way of writing it is to use an INNER JOIN

SELECT [StoreTransactionID],[TransactionDate],[StoreTransactions.StoreID]
FROM StoreTransactions INNER JOIN Store ON StoreTransactions.StoreID=Store.StoreID

This may be more efficient in some RDBMSs.

If your Store query also includes a WHERE clause, you can just add that to the query above.

mdma
Thanks guys. Yes my bad I mixed up the SQL command.