使用T-SQL使用参数获取当前周

时间:2014-12-24 08:56:34

标签: sql-server tsql reporting-services

我希望在SQL查询中有一个函数,它将使用参数显示SSRS 2005中的当前周。我已经声明了两个变量@FromDate和@ToDate。我在下面的where子句中使用这两个变量

where SH.[] between CONVERT(datetime, @FromDate, 105) and CONVERT(datetime, @ToDate, 105)

如何使用@FromDat和@ToDate显示当前周?我可以帮忙吗?

Thankss

1 个答案:

答案 0 :(得分:0)

          CREATE TABLE dbo.TestDates (
            SaleID TINYINT IDENTITY(1,1),
            Amount NUMERIC(9,2),
            SaleDate DATETIME
            );

            GO

            INSERT INTO dbo.TestDates (Amount, SaleDate)
            VALUES (200.00, '2014-12-15'),
            (130.00, '2014-12-16'),
            (40.00, '2014-12-17'),
            (70.00, '2014-12-18'),
            (590.00, '2014-12-19')



            -----------------------------------------
 CREATE FUNCTION dbo.uspGetCurrentWeek(@From VARCHAR(100)
 RETURNS VARCHAR(100)

 AS

 BEGIN

DECLARE @StartCounter TINYINT = 1
DECLARE @EndCounter TINYINT = 5

     WHILE @StartCounter <= @EndCounter
         BEGIN

  DECLARE @String VARCHAR(100) = ( SELECT 'Week' +
                                        CAST(DATEPART(WEEK, SaleDate) AS VARCHAR(2))
                                         FROM dbo.TestDates
                 WHERE SaleDate = @From )
        SET @StartCounter = @StartCounter +1
                       END
              RETURN @String
      END
            --------------

            -----Test data ----
            SELECT *, dbo.uspGetCurrentWeek('2014-12-15')
            FROM dbo.TestDates;
            ---------------------------------