我知道在SQL Server中,可以使用没有FROM子句的SELECT子句,并创建一个包含一行和一列的表
SELECT 1 AS n;
但我只是想知道,是否可以使用没有FROM子句的SELECT子句来创建
包含一列多行的表
包含多列和一行的表
包含多列和多行的表
我尝试了许多组合,例如
SELECT VALUES(1, 2) AS tableName(n, m);
没有成功。
答案 0 :(得分:3)
您可以使用CTE并使用union
(如果您想要显示重复项,请使用union all
)
Rextester Sample for all 3 scenarios
一列多行
with tbl1(id) as
(select 1 union all
select 2)
select * from tbl1;
一行多列
with tbl2(id,name) as
(select 1,'A')
select * from tbl2;
多列和多行
with tbl3(id,name) as
(select 1,'A' union all
select 2,'B')
select * from tbl3;
答案 1 :(得分:2)
-- One column, multiple rows.
select 1 as ColumnName union all select 2; -- Without FROM;
select * from ( values ( 1 ), ( 2 ) ) as Placeholder( ColumnName ); -- With FROM.
-- Multiple columns, one row.
select 1 as TheQuestion, 42 as TheAnswer; -- Without FROM.
select * from ( values ( 1, 42 ) ) as Placeholder( TheQuestion, TheAnswer ); -- With FROM.
-- Multiple columns and multiple rows.
select 1 as TheQuestion, 42 as TheAnswer union all select 1492, 12; -- Without FROM.
select * from ( values ( 1, 2 ), ( 2, 4 ) ) as Placeholder( Column1, Column2 ); -- With FROM.
答案 2 :(得分:1)
您可以使用UNION
关键字
create table tablename as select 1 as n,3 as m union select 2 as n,3 as m
在Oracle中它将是双重的:
create table tablename as select 1 as n,3 as m from dual union select 2 as n,3 as m from dual
答案 3 :(得分:1)
您可以使用UNION运算符:
CREATE TABLE AS SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;
UNION运算符默认情况下仅选择不同的值。要允许重复值,您可以使用UNION ALL 结果集中的列名通常等于UNION中第一个SELECT语句中的列名。
答案 4 :(得分:1)
试试这个:
--1) a table with one column and multiple rows
select * into tmptable0 from(
select 'row1col1' as v1
union all
select 'row2col1' as v1
) tmp
--2) a table with multiple columns and one row
select 'row1col1' as v1, 'row1col2' as v2 into tmptable1
--3) a table with multiple columns and multiple rows
select * into tmptable2 from(
select 'row1col1' as v1, 'row1col2' as v2
union all
select 'row2col1' as v2, 'row2col2' as v2
) tmp
答案 5 :(得分:0)
一个人可以创建一个视图,然后在需要时可以查询它
-- 一列多行表格
create view vw1 as
(
select 'anyvalue' as col1
union all
select 'anyvalue' as col1
)
select * from vw1
-- 多列多行表格
create view vw2 as
(
select 'anyvalue1' as col1, 'anyvalue1' as col2
union all
select 'anyvalue2' as col1, 'anyvalue2' as col2
)
select * from vw2