平时表

时间:2014-02-03 12:01:11

标签: sql-server tsql sql-server-2005

我正在尝试创建一个sproc,它会喷出一个用户友好时间段的动态平面表,以便在其他地方使用。这是我的第一次尝试:

CREATE PROCEDURE aaLogi.GetQuickPeriods

AS
BEGIN
    SET NOCOUNT ON;
    DECLARE @Today DATETIME;
    DECLARE @WeekStart DATETIME;

    SET @Today = GETDATE();
    SET @WeekStart = DATEADD(WEEK, DATEDIFF(WEEK, '19050101', @Today), '19050101'); 

        DECLARE @QuickPeriods TABLE
    (
      QuickPeriod NVARCHAR(max), 
      FromDateTime DATETIME,
      ToDateTime DATETIME
    )

    INSERT INTO @QuickPeriods (QuickPeriod, FromDateTime, ToDateTime)
    VALUES ('Today', @Today, @Today) 

    INSERT INTO @QuickPeriods (QuickPeriod, FromDateTime, ToDateTime)
    VALUES ('This Week', @WeekStart, DATEADD(day, 7, @WeekStart)) 

    INSERT INTO @QuickPeriods (QuickPeriod, FromDateTime, ToDateTime)
    VALUES ('Week to Date', @WeekStart, @Today)

    SELECT * FROM @QuickPeriods

END
GO

这一切都非常程序化。有更多基于集合/有效的方式吗?对不起,我的TSQL还不是很流畅......

1 个答案:

答案 0 :(得分:1)

如果它能为您提供预期的结果,那么您的插入语句可以更加简化,其余对我来说很好看

INSERT INTO @QuickPeriods (QuickPeriod, FromDateTime, ToDateTime)
SELECT 'Today'      , @Today    , @Today
UNION ALL
SELECT 'This Week'  , @WeekStart, DATEADD(day, 7, @WeekStart)
UNION ALL
SELECT 'Week to Date', @WeekStart, @Today
  

为什么QuickPeriod字段是NVARCHAR(最大)?最长的字符串值是   我认为'Week to Date'是12个字符,所以为什么不使用呢   NVARCHAR(12)或(15)。