简体   繁体   中英

Assign Values of a column in SubQuery in SQL

I am trying to do following in SQL Server:

SELECT 
    PRODUCER_NAME, PRODUCER_ID,
    (SELECT @X = @X + PRODUCT_NAME 
     FROM PRODUCT 
     WHERE PRODUCER_ID = PRODUCER.ID) 
FROM 
    PRODUCER

There are two tables. Producer table is list of all producers. Product table stores product produced by producers. @x is varchar variable

Basically I want a list of all products, comma-separated by producer.

For example

Producer     Products
--------     --------------------------
P1           ProductA,ProductB,ProductC
P2           ProductD,ProductE

I don't know if this is possible this way. Do anyone know how to do this without joining tables?

I don't have a way for you to assign multiple output comma-separated lists to a single varchar variable, but maybe you don't actually need that anyway. Try this:

SELECT 
  Producer = p.PRODUCER_NAME, 
  Products = STUFF((
    SELECT ',' + pr.PRODUCT_NAME 
      FROM dbo.PRODUCT AS pr
      WHERE pr.PRODUCER_ID = p.PRODUCER_ID 
      FOR XML PATH('')).value('.[1]','nvarchar(max)'),1,1,'')
FROM dbo.PRODUCER AS p;

If you want to concatenate names, you can do this:

select
    P.PRODUCER_NAME, P.PRODUCER_ID,
    stuff(
        (
            select ',' + T.PRODUCT_NAME
            from PRODUCT as T
            where T.PRODUCER_ID = P.PRODUCER_ID
            for xml path(''), type
        ).value('.', 'nvarchar(max)')
    , 1, 1, '') as PRODUCT_NAMES
from PRODUCER as P

Two notes:

  1. Always use the table aliases for such a queries. To see why - delete alias name from query and drop PRODuCER_ID from PRODUCT table.
  2. Use value method instead of implicit conversion to nvarchar to correctly work with names like 'Product & 1'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM