SQL Server 2005中的交叉连接值

4
我使用的是SQL Server 2005,但遇到了错误:

在“VALUES”关键字附近有语法错误。

当我尝试运行以下查询时会出现此错误:

  SELECT T.N 
  FROM Table
  CROSS JOIN (VALUES(1),(2),(3),(4),(5),(6),(7),(8),(9)) as T(N)
  WHERE 1 = 1

但在SQL Server 2008中可以正常工作,而在SQL Server 2005中需要做些什么才能让它正常工作呢?


3
“表值构造函数”是在 SQL 2008 中引入的;我认为这个链接 https://www.simple-talk.com/sql/sql-training/table-value-constructors-in-sql-server-2008/ 对此非常有用。 - Paul Maxwell
1个回答

7

只需使用selectunion all即可:

SELECT T.N
FROM Table CROSS JOIN
     (select 1 as n union all select 2 union all select 3 union all select 4 union all select 5 union all
      select 6 union all select 7 union all select 8 union all select 9
     ) as T(N)
WHERE 1=1;

或者,使用递归CTE,这样您就不必输入值:
with t(n) as
      select 1 as n
      union all
      select n + 1
      from t
      where n < 9
     )
select t.n
from table1 cross join
     t
where 1 = 1;

1
是的,我考虑过了,但是union all?真的吗? - Control Freak

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接