在过程中,我需要生成两个或多个查询,从而生成相同的列,并将结果行合并到一个返回表中。实施例
CREATE PROC tmpProc
AS
BEGIN
-- Making first query
SELECT * INTO #resultTable FROM tableOne;
-- Making second query, resulting columns are totally the same
SELECT * INTO #resultTable FROM tableTwo;
-- Return rowset from temporary table
SELECT * From #resultTable;
END
但是这种类型的过程失败了,因为There is already an object named #resultTable in the database
答案 0 :(得分:1)
如果两个表中的列相同,这将有效。
CREATE PROC tmpProc
AS
BEGIN
-- Making first query
SELECT * FROM tableOne;
UNION ALL
SELECT * FROM tableTwo;
END
答案 1 :(得分:1)
CREATE PROC tmpProc
AS
BEGIN
-- Making first query
SELECT * INTO #resultTable FROM tableOne;
-- Making second query, resulting columns are totally the same
INSERT INTO #resultTable SELECT * FROM tableTwo;
-- Return rowset from temporary table
SELECT * From #resultTable;
END
答案 2 :(得分:1)
以下是两个样本:
IF OBJECT_ID('tempdb..#resultTable') IS NOT NULL DROP TABLE #resultTable
------ 1 use insert into select---------------------
SELECT * INTO #resultTable FROM tableOne;
INSERT INTO #resultTable SELECT * FROM tableTwo
------ 1 use union ---------------------
SELECT * INTO #resultTable FROM (
SELECT * FROM tableOne
UNION ALL
SELECT * FROM tableTwo
) AS t
答案 3 :(得分:0)
试试这个
CREATE PROC tmpProc
AS
BEGIN
select * into #resultTable from (
SELECT col1,col2,col3...coln FROM tableOne;
union all
SELECT col1,col2,col3...coln FROM tableTwo;
) as a
SELECT * From #resultTable;
END