如何在存储过程中将两个MS SQL Server表合并为一个表

时间:2014-02-19 15:47:47

标签: sql sql-server stored-procedures union user-defined-types

我在SQL Server 2008R2中有一个存储过程,它将两个用户定义的表类型作为参数。这些类型中的每一个都是一个包含一系列ID的简单表:

CREATE TYPE [dbo].[Ids] AS TABLE(
    [Id] [int] NULL
)

我想结合传入的两个参数来实现以下结果:

DECLARE 
@Table1 TABLE (Id INT )

DECLARE
@Table2 TABLE (Id INT )


INSERT INTO @Table1 VALUES (1)
INSERT INTO @Table1 VALUES (2)

INSERT INTO @Table2 VALUES (11)
INSERT INTO @Table2 VALUES (22)


SELECT * FROM @Table1
SELECT * FROM @Table2


DECLARE
@Combined TABLE (T1 INT, T2 INT)

-- TODO: Magically combine the two tables

SELECT * FROM @Combined

-- Output would be the following

1, 11
1, 22
2, 11
2, 22

1 个答案:

答案 0 :(得分:2)

您似乎想要cross join

insert into @Combined(t1, t2)
    select t1.id, t2.id
    from @Table1 t1 cross join
         @Table2 t2;