根据特定条件生成动态行和标志

时间:2014-08-14 14:25:22

标签: sql sql-server

我试图生成动态SQL结果(不基于任何表)。

这就是我现在所拥有的:

SELECT datepart(year,getdate()) as [VALUE], 
'datepart(year,getdate()) as [DESCRIPTION], null as DEFAULT_VALUE

结果是:

VALUE       DESCRIPTION DEFAULT_VALUE
----------- ----------- -------------
2014        2014        NULL

我的目标:

VALUE       DESCRIPTION DEFAULT_VALUE
----------- ----------- -------------
2013        2013        False  
2014        2014        True
2015        2015        False

所以我想知道的是,是否有任何方法可以添加新列DEFAULT_VALUE,并使其足够聪明以将默认值设置为当前年份?

2 个答案:

答案 0 :(得分:1)

很好地取决于你想要获得多少花哨,而不知道更多的下划线问题。这应该工作

declare @result table (VALUE int, DESCRIPTION int, DEFAULT_VALUE char(5))

declare @year int = -1
declare @workingYear datetime

select  @workingYear = dateadd(year, @year, getdate())

while @year < 2
begin

select  @workingYear = dateadd(year, @year, getdate())

    insert into @result values (
    datepart(year,@workingYear), 
    datepart(year,@workingYear),  
    case 
        when (datepart(year,@workingYear) = datepart(year,getdate())) then 
            'True'
        else
            'False'
        end)
set @year = @year + 1
end

select * from @result

这会产生结果

    VALUE   DESCRIPTION DEFAULT_VALUE
    2013    2013        False
    2014    2014        True 
    2015    2015        False

答案 1 :(得分:0)

您可能需要查看Tally Table。链接在这里: http://www.sqlservercentral.com/articles/T-SQL/62867/

declare @result table(
    value int,
    description int,
    default_value varchar(5)
)

declare @current_year int
set @current_year = datepart(year,getDate())

-- create your tally table --
with 
    e1 as(select 1 as N union all select 1), -- 2 rows
    e2 as(select 1 as N from e1 as a, e1 as b), -- 4 rows
    e3 as(select 1 as N from e2 as a, e2 as b), -- 16 rows
    e4 as(select 1 as N from e3 as a, e3 as b), -- 256 rows
    e5 as(select 1 as N from e4 as a, e4 as b), -- 65536 rows
    tally as (select row_number() over(order by N) as N from e5
)
insert into @result
select top 3 -- replace 3 with number of rows you want
    N, 
    N,
    case
        when N = @current_year then 'True'
        else 'False'
    end
from tally
where 
    N >= 2013 --start year

select * from @result