x

Retrieve columns from multiple tables

I have a requirement that i have two tables 1.customer(cust_id(PK),addr_id,email) 2.customer_order(order_id,cust_id(FK))

My requirement is to get email and order_ids(order_ids in comma seperated value for each cust_id)
more ▼

asked Nov 24, 2011 at 04:18 AM in Default

sumanbanda gravatar image

sumanbanda
0 1 1 1

(comments are locked)
10|1200 characters needed characters left

1 answer: sort voted first

I believe you want to do something like this

DECLARE @customer TABLE 
(cust_id INT PRIMARY KEY,
email VARCHAR(50)
) 
DECLARE @customer_order TABLE (order_id INT PRIMARY KEY,cust_id INT)

-- TEMPORARY DATA INSERTION

INSERT @customer
        (
         [cust_id]
        ,[email]
        )
SELECT 1, 'a@mail.com'
UNION ALL
SELECT 2, 'b@mail.com'

INSERT @customer_order
        (
         [order_id]
        ,[cust_id]
        )
SELECT 1, 1
UNION ALL
SELECT 2, 1
UNION ALL
SELECT 3,1
UNION ALL
SELECT 4,2
UNION ALL
SELECT 5,2


-- FINAL OUTPUT
SELECT  [cust_id]
,       email
,       STUFF(( SELECT  ',' + CAST([order_id] AS VARCHAR(50))
                FROM    @customer_order AS CO
                WHERE   CO.[cust_id] = C.[cust_id]
              FOR
                XML PATH('')
              ), 1, 1, '')
FROM @customer AS C
more ▼

answered Nov 24, 2011 at 04:40 AM

Usman Butt gravatar image

Usman Butt
13.9k 6 8 14

thanks for the answer which i am looking for exactly.....
Nov 24, 2011 at 05:27 AM sumanbanda
(comments are locked)
10|1200 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

New code box

There's a new way to format code on the site - the red speech bubble logo will automatically format T-SQL for you. The original code box is still there for XML, etc. More details here.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

SQL Server Central

Need long-form SQL discussion? SQLserverCentral.com is the place.

Topics:

x1951

asked: Nov 24, 2011 at 04:18 AM

Seen: 576 times

Last Updated: Nov 24, 2011 at 04:18 AM