交叉加入'n'次表

时间:2010-05-11 21:40:48

标签: sql sql-server sql-server-2008

可以编写一个泛型函数/ procedure / select / somethingElse来反对自己'n'次表连接表吗? (是的,'n'是给定的参数:)

你会怎么做?


示例

有这个表:

 Value
-------
   1
   2
   3 

交叉加入2次,将返回:

 Value  | Value
------------------
    1       1
    1       2
    1       3
    2       1
    2       2
    2       3
    3       1
    3       2
    3       3

4 个答案:

答案 0 :(得分:5)

使用动态SQL,SQL Server 2005+(@ table_name和@numCrossJoins是存储过程参数):

DECLARE @upperLimit INT
    SET @upperLimit = 1

DECLARE @SQL NVARCHAR(MAX)
    SET @SQL = 'SELECT * FROM '+ @table_name +' '

BEGIN 

  WHILE (upperLimit <= @numCrossJoins)
  BEGIN

    SET @SQL = @SQL + 'CROSS JOIN '+ QUOTENAME(@table_name) +' '

    SET @upperLimit = @upperLimit + 1
  END

  EXEC sp_executesql @SQL

END

答案 1 :(得分:3)

您可以生成动态sql以根据需要输出任意数量的交叉连接:

create table #t (value int)

insert into #t values (1)
insert into #t values (2)
insert into #t values (3)

declare @n int
set @n = 4

declare @sql varchar(max)
set @sql = 'SELECT * FROM #t t'
declare @i int
set @i = 0
while (@i <= @n)
begin
    set @sql = @sql + ' cross join #t t' + CAST(@i as varchar)
    set @i = @i + 1
end

print @sql
execute(@sql)

drop table #t

答案 2 :(得分:2)

试试这个:

SET @SQL = 'SELECT * FROM ' + replicate('[' + @table_name + '],', @N);

set @SQL = LEFT(LEN(@SQL) - 1);

EXEC sp_executesql @SQL;

答案 3 :(得分:1)

如果你需要提出所有可能的排列,这里有一个例子:

All Permutations For A String