views:

58

answers:

2

Hi there

I have 3 tables: Customer, CustomerTypes, CustomerCustomerTypes. CustomerCustomerTypes is basically is a bridge table between the Customer and CustomerTypes.

Table structure: Customers: CustomerID CustomerName

CustomerTypes: CustomerTypeID CusctomerTypeName

CustomerCustomerTypeID CustomerID CustomerTypeID

Sample Data: Customers:

1, ABC
2, CBA

CustomerTypes:

1, Broadcast
2, Banking
3, Retailer

CustomerCustomerTypes:

1, 1
2, 2
2, 3

I want to be able to return query as follow:

ABC; "Broadcasting"
CustomerCustomerTypes; "Banking, Retailer"

as well as to be able to search that string let say "CustomerTypeID = 2"

It will be ruturned as :

CustomerCustomerTypes; "Banking, Retailer"

I can do this with cursor type of query BUT i am just wondering maybe there is a better way.

Thanks

+1  A: 

A SQL Server FOR XML query will give you what you want. I haven't had a chance to check the below but it should point you in the right direction.

SELECT c1.CustomerTypeId,
       ( SELECT CustomerTypeName + ',' 
           FROM CustomerTypes c2
          WHERE c2.CustomerTypeId = c1.CustomerTypeIdId
          ORDER BY CustomerTypeName
            FOR XML PATH('') ) AS CustomerTypess
      FROM CustomerCustomerTypes c1
      GROUP BY CustomerTypeId;
Dave Barker
+2  A: 

Use:

SELECT c.customername,
       STUFF((SELECT ','+ ct.customertypename
               FROM CUSTOMERTYPES ct
               JOIN CUSTOMERCUSTOMERTYPES cct ON cct.customertypeid = ct.customertypeid
              WHERE cct.customerid = C.customerid
           GROUP BY ct.customertypename
            FOR XML PATH('')), 1, 1, '')
 FROM CUSTOMERS c

To be able to search for a specific customer type:

SELECT c.customername,
       STUFF(SELECT ','+ ct.customertypename
               FROM CUSTOMERTYPES ct
               JOIN CUSTOMERCUSTOMERTYPES cct ON cct.customertypeid = ct.customertypeid
              WHERE cct.customerid = C.customerid
           GROUP BY ct.customertypename
            FOR XML PATH(''), 1, 1, '')
 FROM CUSTOMERS c
 JOIN CUSTOMERCUSTOMERTYPES cct ON cct.customertypeid = ct.customertypeid
WHERE cct.customertypeid = @customertypeid
OMG Ponies
Be aware that FOR XML PATH is only supported 2005+
OMG Ponies
Thanks OMG Ponies. I made a revision on your code, it should have a bracket between SELECT in STUFF section. Thanks again .. I knew it there is a better way than cursor.
dewacorp.alliances
@dewacorp: Sorry about that - corrected.
OMG Ponies