TSQL表变量初始化

时间:2012-09-25 18:48:16

标签: sql tsql lookup-tables table-variable

我有以下TSQL表变量:

declare @NumDaysMonth table
(
   month_id smallint,
   num_days smallint
)

我只想快速查看每个月的天数。如何像C数组一样初始化此表:

int numDaysMonth[] = {31, 28, 30, ... , 31};

5 个答案:

答案 0 :(得分:26)

嗯,你不能。你能做的最好就是这样

Insert Into @NumDaysMonth
Values 
(1,31),
(2,28),
(3,31),
...
(12,31);

然后检索可能类似于

DECLARE @LookItUp int

SELECT @LookItUp = num_days 
FROM @NumDaysMonth
WHERE month_Id = 12;

PRINT @LookItUp 

SQL Fiddle Demo

答案 1 :(得分:3)

以下内容未解决OP初始化表的问题。欢迎您将其视为格式化评论。

奇怪的查找表很方便的技巧是动态创建虚拟表:

declare @Foo as Table ( Month Int )
insert into @Foo values ( 1 ), ( 3 ), ( 9 )

select *
  from @Foo as F inner join
    ( select month_id, num_days
      from ( values
      ( 1, 31 ), ( 2, 28 ), ( 3, 31 ), ( 4, 30 ), ( 5, 31 ), ( 6, 30 ),
      ( 7, 31 ), ( 8, 31 ), ( 9, 30 ), ( 10, 31 ), ( 11, 30 ), ( 12, 31 )
      ) as NumDaysMonth( month_id, num_days ) ) as NumDaysMonth on
    NumDaysMonth.month_id = F.Month

为了获得一个月内的天数,我更倾向于创建一个以年和月为单位并返回正确值的函数。当我需要从一些代码快速翻译到可读的东西时,un-table很方便。

如果您需要在一个地方多次参考仿表:

; with NumDaysMonth as (
  ( select month_id, num_days
    from ( values
      ( 1, 31 ), ( 2, 28 ), ( 3, 31 ), ( 4, 30 ), ( 5, 31 ), ( 6, 30 ),
      ( 7, 31 ), ( 8, 31 ), ( 9, 30 ), ( 10, 31 ), ( 11, 30 ), ( 12, 31 )
      ) as NumDaysMonth( month_id, num_days ) ) ),
  FooMonths as (
    select *
      from @Foo as F inner join
        NumDaysMonth as NDM on NDM.month_id = F.Month ),
  FooWithFollowingMonths as (
    select *
      from FooMonths
    union
    select *
      from @Foo as F inner join
        NumDaysMonth as NDM on NDM.month_id = F.Month + 1 )
  select *
    from FooWithFollowingMonths

除此之外,查找表应该保存为真正的表或表值函数。

答案 2 :(得分:2)

仅供参考这种数组有点不完整,因为它不会随着闰年的变化而变化?例如今年2月有29天。

以下为您提供了0索引(如C#)的列表,适用于当前年份。

declare @NumDaysMonth table
(
   month_id smallint,
   num_days smallint
)
insert @NumDaysMonth
select m.m, day(dateadd(m,m+1,y)-1)
from
(select CAST(right(year(getdate()),4)+'0101' as datetime)) y(y)
cross join
(select 0 union all
 select 1 union all
 select 2 union all
 select 3 union all
 select 4 union all
 select 5 union all
 select 6 union all
 select 7 union all
 select 8 union all
 select 9 union all
 select 10 union all
 select 11) m(m)

select * from @NumDaysMonth

-- results
MONTH_ID    NUM_DAYS
0   31
1   29
2   31
3   30
4   31
5   30
6   31
7   31
8   30
9   31
10  30
11  31

如果您需要任何其他年份,请将年份放入Y子查询中,例如: (select cast('19990101' as datetime))

答案 3 :(得分:2)

这很容易。使用declare @NumDaysMonth table ( month_id smallint identity primary key, num_days smallint ); insert into @NumDaysMonth (num_days) values (31), (28), (31), (30), (31), (30), (31), (31), (30), (31), (30), (31); select * from @NumDaysMonth; 生成自动递增的数字。

(12 row(s) affected)
month_id num_days
-------- --------
1        31
2        28
3        31
4        30
5        31
6        30
7        31
8        31
9        30
10       31
11       30
12       31

(12 row(s) affected)

- >

identity
如果需要,

{{1}}可以使用不同的起始编号或增量进行播种。

答案 4 :(得分:0)

可以使用UDF,并使其可以调整任何一年。

-- =============================================
-- Author:      Alexander Melnichuk for StackOverflow.com
-- Create date: 2013-03-12
-- Description: Number of days in a month
-- =============================================
CREATE FUNCTION [dbo].[f_NumDaysMonth] (
    @Year datetime = NULL   -- Month and day are ignored. Null gets current year. 
)
RETURNS 
@Ret TABLE (
    month_id smallint, 
    num_days smallint
)
AS
BEGIN
    SET @Year = convert(datetime, convert(varchar(4), 
                    isnull(@Year, getdate()), 112) + '0101', 112)

    WITH  
    seq AS  
    (--==== Returns table of values from 1 to 12
    SELECT TOP (12)
        N = ROW_NUMBER() OVER (ORDER BY t1.Object_ID)
    FROM Master.sys.All_Columns t1          -- There are certainly more than 12 columns in your Master database ;)
    --CROSS JOIN Master.sys.All_Columns t2  -- Uncomment if you need more values. Not this time though.
    )  

    INSERT INTO @Ret
    SELECT N, 
        day(dateadd(day, -1, dateadd(month, N, @Year)))
    FROM seq
    RETURN 
END

用法:

SELECT * FROM [dbo].[f_NumDaysMonth] ('20130101')

执行时间 - 0毫秒。 :)