문제

I'm trying to create a comma separated list and I'm using a derived table. But I cannot declare the variable within the LEFT OUTER JOIN... how can I do this?

    LEFT OUTER JOIN (

               DECLARE @String AS VARCHAR(MAX) = NULL
               SELECT @String = COALESCE(@String + ', ','') + Name
                 FROM MyTable
               SELECT @String, Col1
                 FROM MyTable
                GROUP BY Col1

    ) AS T8
   ON This = That

It gives me an error on the Declare keyword that says, Incorrect Syntax.

Thanks!

도움이 되었습니까?

해결책

You cannot declare a variable inside a derived table.

But you may declare it outside of the statement and use it in the same way as you did in your example

다른 팁

Your requirement doesn't make sense because the variable can't really be used inside the table variable. And if you want to use it after the table variable, it still doesn't make sense... do you expect multiple instances of the variable, once for each distinct value of Col1? Maybe you meant this:

LEFT OUTER JOIN
(
  SELECT Col1, String = STUFF((
     SELECT ',' + Name
        FROM dbo.MyTable AS i 
        WHERE i.Col1 = o.Col1 
        FOR XML PATH(''), TYPE).value('.', 'nvarchar(max)'),1,1,'')
  FROM dbo.MyTable AS o
  GROUP BY Col1
) AS T8
ON This = That

However, T8 kind of scares me a little. How many tables are already involved in this join?

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top