如何使用循环将varchar值插入表中

时间:2014-06-18 06:46:50

标签: sql-server-2008

我有一张名为ATMONTH的桌子,我需要检查每个月的顾客数量

表结构就像

CREATE TABLE [dbo].[ATMONTH](
[ID] [bigint] IDENTITY(1,1) NOT NULL,
[Month] [varchar](50) NULL,
[COUNT OF CUSTOMER] [varchar] (50) NULL,
[RefMonthStart] [varchar](50) NULL, 
[RefMonthEnd] [varchar](50) NULL) 

我正在接受像

这样的输出
  

1 1月3000 0 30

     

2 2Month 4500 31 60

     

3 3month 4000 61 90

     

4 4Month 6000 91 120

     

     

     

     

24 24月...... .. ..

     

25> 24Month .. .. ..

其中客户的数量我指的是其他表..这里只有月份,refmonthstart和

refmonthend列必须手动插入refmonthstart和refmonthend列

是一个月内的天数

我将如何做???

先谢谢

1 个答案:

答案 0 :(得分:1)

尝试以下查询

DML:

CREATE TABLE [dbo].[ATMONTH](
    [ID] [bigint] IDENTITY(1,1) NOT NULL,
    [Month] [varchar](50) NULL,
    [COUNT OF CUSTOMER] [varchar] (50) NULL,
    [RefMonthStart] [varchar](50) NULL, 
    [RefMonthEnd] [varchar](50) NULL)

INSERT INTO [dbo].[ATMONTH]([Month])
VALUES ('Jan'),
('Feb'),
('Mar'),
('Apr'),
('May'),
('Jun'),
('Jul'),
('Aug'),
('Sep'),
('Oct'),
('Nov'),
('Dec');


CREATE TABLE dbo.MonthsAndDays
(
    [Month] VARCHAR(3),
    Days SMALLINT
)

INSERT INTO dbo.MonthsAndDays([Month],Days)
VALUES ('Jan',31),
('Feb',28),
('Mar',31),
('Apr',30),
('May',31),
('Jun',30),
('Jul',31),
('Aug',31),
('Sep',31),
('Oct',30),
('Nov',30),
('Dec',31);

查询:

DECLARE @refmonthstart INT = 0

;WITH CTE AS
(
    SELECT a.ID,
           a.Month,
           a.[COUNT OF CUSTOMER],
           a.[RefMonthStart],
           a.[RefMonthEnd],
           b.Days Days,
           ROW_NUMBER() OVER ( ORDER BY a.[ID] ASC) i
    FROM [dbo].[ATMONTH] a
    INNER JOIN dbo.MonthsAndDays b
    ON a.[Month] = b.[Month]
)
,
ResultSet AS
(
    SELECT ID,
           Month,
           [COUNT OF CUSTOMER],
           @refmonthstart AS RefMonthStart,
           Days + @refmonthstart AS RefMonthEnd,
           i
    FROM CTE
    WHERE i = 1

    UNION ALL

    SELECT  T.ID,
            T.Month,
            T.[COUNT OF CUSTOMER],
            R.RefMonthEnd + 1,
            T.Days + R.RefMonthEnd,
            T.i
    FROM ResultSet R
    INNER JOIN CTE T
    ON  R.i + 1 = T.i 

)
SELECT *
FROM ResultSet
OPTION (MAXRECURSION 1000)

查询将递归计算refmonthstart和refmonthend值。根据表中的行数设置MAXRECURSION值。 您可以设置声明@refmonthstart的初始refmonthstart值,我已将其设置为0(零)