Question

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!

Was it helpful?

Solution

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

OTHER TIPS

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?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top