仅使用select语句模拟表

时间:2019-01-07 16:01:22

标签: sql sql-server select

Simulate a table with multiple rows just with SELECT statement类似的问题-该问题要求由多行组成的单列

如何模拟具有多列和行的表?

我已经走到了这一步(对于多列单行):

SELECT 'John Doe' AS [Customer Name],
       '31' AS [Customer Age],
       'pizza' AS [Food]

但是不确定如何获取多行数据。

使用sql-server

3 个答案:

答案 0 :(得分:5)

使用values表构造函数:

SELECT v.*
FROM (VALUES ('John Doe', 31, 'pizza'),
             ('John Doe', 31, 'pizza')
     ) v(customer_name, customer_age, food);

注意:

  • 请勿在列名称中使用空格。它们只会使编写查询变得更加困难。
  • age是一本糟糕的书。相反,您应该有出生日期。
  • 只需使用所需的值重复值列表。

答案 1 :(得分:2)

CROSS JOIN用作快速破解

SELECT 'John Doe' AS [Customer Name],
       '31' AS [Customer Age],
       'pizza' AS [Food]
from (select 1 as x) x
cross join (select 1 as ID union select 2 union select 3) y

或者根据您的评论,最好创建一些虚拟数据...

declare @table table ([Customer Name] varchar(64), [Customer Age] int, [Food] varchar(64))
insert into @table
values
('John Doe',31,'Pizza'),
('New Doe',15,'Fish'),
('Frank Doe',66,'Crackers'),
('John McGee',91,'Sausage')

select * from @table

答案 2 :(得分:2)

选项1: UNION ALL

SELECT
    [Customer Name] = 'John Doe',
    [Customer Age] = 31,
    Food = 'pizza'
UNION ALL
SELECT
    [Customer Name] = 'Jane Doe',
    [Customer Age] = 25,
    Food = 'cake'

您只需要在第一组上提供列名:

SELECT
    [Customer Name] = 'John Doe',
    [Customer Age] = 31,
    Food = 'pizza'
UNION ALL
SELECT 'Jane Doe', 25, 'cake' UNION ALL
SELECT 'Jane Doe', 16, 'coke' UNION ALL
SELECT 'Jane Doe', 19, 'salad'

选项2: VALUES

SELECT
    T.[Customer Name],
    T.[Customer Age],
    T.Food
FROM
    (VALUES
    ('John Doe', 31, 'pizza'),
    ('Jane Doe', 25, 'cake')
    ) AS T([Customer Name], [Customer Age], Food)

我建议第二种方法,因为您可以强制执行所需的数据类型,例如:

SELECT
    [Customer Name] = CONVERT(VARCHAR(50), T.[Customer Name]),
    [Customer Age] = CONVERT(TINYINT, T.[Customer Age]),
    Food = CONVERT(VARCHAR(100), T.Food)
FROM
    (VALUES
    ('John Doe', 31, 'pizza'),
    ('Jane Doe', 25, 'cake')
    ) AS T([Customer Name], [Customer Age], Food)

使用VALUES,您还可以直接与其他表联接(或应用函数),而无需将SELECT包装在CTE或子查询中。

但是,如果要出于测试目的模拟表(特别是要测试性能),建议不要使用 ,因为这两种方法都要求您大大改变您当前正在测试的语句。为此,只需创建一个与您要模拟的表完全相同的临时表,然后在其中加载数据即可。