SQL:如何在派生表中声明变量?
我正在尝试创建一个逗号分隔的列表,并且正在使用派生表。但我无法在 LEFT OUTER JOIN 中声明变量...我该怎么做?
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
它在 Declare
关键字上给我一个错误,提示语法错误。
谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不能在派生表内声明变量。
但是您可以在语句之外声明它并以与示例中相同的方式使用它
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
您的要求没有意义,因为该变量不能真正在表变量内部使用。如果您想在表变量之后使用它,它仍然没有意义...您是否期望变量的多个实例,对于 Col1 的每个不同值一次?也许你的意思是这样的:
但是,T8 有点让我害怕。此连接已涉及多少张表?
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:
However, T8 kind of scares me a little. How many tables are already involved in this join?