sql触发日期范围与工作日

时间:2015-03-20 20:29:03

标签: sql sql-server date triggers sql-server-2012

我在MSSQL(2012)DB(“tblA”和“tblB”)上有2个表格。在“tblA”上插入后,我想要一个触发器在“tblB”上自动生成STARTDATE和ENDDATE之间的日期从“tblA”开始但仅在“tblA”上选择的工作日

例如“tblA”:

tblA_ID: 99
CAT: TEXT1
STARTDATE: 01/01/2015
ENDDATE: 31/01/2015
MONDAY: true
TUESDAY: false
WEDNESDAY: false
THURSDAY: false
FRIDAY: true
SATURDAY: false
SUNDAY: false

“tblB”应该

 1   99    TEXT1   02/01/2015 (=Friday)
 2   99    TEXT1   04/01/2015 (=Monday)
 3   99    TEXT1   09/01/2015 (=Friday)
 4   99    TEXT1   11/01/2015 (=Monday)
 5   99    TEXT1   16/01/2015 (=Friday)
 6   99    TEXT1   28/01/2015 (=Monday)
 7   99    TEXT1   23/01/2015 (=Friday)
 8   99    TEXT1   25/01/2015 (=Monday)
 9   99    TEXT1   30/01/2015 (=Friday)




    CREATE TABLE [dbo].[tblA]
(
    [tblA_ID] INT NOT NULL IDENTITY,
    [tblA_CAT] NVARCHAR(50) NULL, 
    [tblA_STARTDATE] DATE NULL, 
    [tblA_ENDDATE] DATE NULL, 
    [tblA_MONDAY] BIT NULL, 
    [tblA_TUESDAY] BIT NULL, 
    [tblA_WEDNESDAY] BIT NULL, 
    [tblA_THURSDAY] BIT NULL, 
    [tblA_FRIDAY] BIT NULL, 
    [tblA_SATURDAY] BIT NULL, 
    [tblA_SUNDAY] BIT NULL, 
    CONSTRAINT [PK_tblA] PRIMARY KEY ([tblA_ID]), 
)

CREATE TABLE [dbo].[tblB]
(
    [tblB_ID] INT NOT NULL IDENTITY,
    [tblA_ID] INT NOT NULL,
    [tblB_CAT] NVARCHAR(50) NULL, 
    [tblB_DATE] DATE NULL, 
    CONSTRAINT [PK_tblB] PRIMARY KEY ([tblB_ID]), 
)

1 个答案:

答案 0 :(得分:0)

此触发器应该适合您。它使用递归公用表表达式生成范围中的所有tblB_DATE值,然后使用case表达式来测试当天的名称是否标记为true。请注意,此部分取决于系统语言,因此如果您不使用英语,则必须根据您的特定语言调整日期名称文字。

递归公用表表达式可以替代日历表,因此如果您有一个适当的表可以作为日期的来源,那么您可以使用它(它应该提供更好的性能)。

请注意,代码缺少错误检查,并且尚未进行优化,因此可能会得到改进。它应该让您了解如何解决问题。

CREATE TRIGGER ins_tblb ON [dbo].[tblA] AFTER INSERT AS
BEGIN

    WITH dates AS (
       SELECT 
          tblA_ID, tbla_CAT, tbla_STARTDATE, tbla_ENDDATE, 
          tbla_MONDAY, tbla_TUESDAY, tbla_WEDNESDAY, tbla_THURSDAY, 
          tbla_FRIDAY, tbla_SATURDAY, tbla_SUNDAY,
          tblA_STARTDATE tblB_DATE
       FROM inserted
       UNION ALL 
       SELECT tblA_ID, tbla_CAT, tbla_STARTDATE, tbla_ENDDATE, 
          tbla_MONDAY, tbla_TUESDAY, tbla_WEDNESDAY, tbla_THURSDAY, 
          tbla_FRIDAY, tbla_SATURDAY, tbla_SUNDAY,
          DATEADD(DAY, 1, tblB_DATE) tblB_DATE
       FROM dates 
       WHERE dates.tblB_DATE <= tblA_ENDDATE
    ) 

    INSERT tblB (tblA_ID, tblB_CAT, tblB_DATE)
    SELECT tblA_ID, tblA_CAT, tblB_DATE
    FROM dates
    WHERE DATENAME(DW,tblB_DATE) IN (
       CASE WHEN tblA_MONDAY = 1 
          THEN N'Monday' END,
       CASE WHEN tblA_TUESDAY = 1 
          THEN N'Tuesday' END,
       CASE WHEN tblA_WEDNESDAY = 1 
          THEN N'Wednesday' END,
       CASE WHEN tblA_THURSDAY = 1 
          THEN N'Thursday' END,
       CASE WHEN tblA_FRIDAY = 1 
          THEN N'Friday' END,
       CASE WHEN tblA_SATURDAY = 1 
          THEN N'Saturday' END,
       CASE WHEN tblA_SUNDAY = 1 
          THEN N'Sunday' END
    )

    ORDER BY tblA_ID, tblB_DATE
    OPTION (MAXRECURSION 0)
END