首页 > 解决方案 > 在查询中创建要加入的浮动表

问题描述

在数据库中,我缺少一些应该提供对类型的引用的基本表;这些是硬编码在软件中的。为了不无休止地编写case语句来更改这些值,我想在每次需要这些数据时复制粘贴一个简单的浮动表。

我对declare类型语句完全陌生,到目前为止,在创建可以粘贴到脚本中的子查询方面还没有运气。结果应该是这样的:

| Type ID |   Period |
----------------------
|      1  |      day |
|      2  |     week |
|      3  |    month |
|      4  |  quarter |
|      5  |     year |

我只是想将此表声明为子查询,以便我可以join在其他包含type ID's

标签: sqlsql-serverssms

解决方案


临时表可能是最简单的方法,因为您可以一步完成:

select 1 as type_id, 'day' as period
into #temp_type_period union all
select 2 as type_id, 'week' union all
select 3 as type_id, 'month' union all
select 4 as type_id, 'quarter' union all
select 5 as type_id, 'year' ;

使用declare,您必须声明表,然后将其插入:

declare @type_period table (
    type_id int,
    period varchar(255)
);

insert into @type_period (type_id, period)
    select 1 as type_id, 'day' as period
    select 2 as type_id, 'week' union all
    select 3 as type_id, 'month' union all
    select 4 as type_id, 'quarter' union all
    select 5 as type_id, 'year' ;

推荐阅读