2017-09-25 193 views
0

我想爲我的參數顯示月份和年份,供最終用戶從下拉列表中進行選擇。SQL Server中參數的月份和年份的下拉列表

例如,開始日期必須在6月2017年結束日期只有一個月,一年getdate()

這是我寫的查詢,但它不是爲我工作

declare @start datetime = '6/1/2017' 
declare @end datetime = getdate() 

select 
    @start = dateadd(M, @start), 
    datename(M, @start) + ' ' + datename(Y, @start) 
where 
    @start < @end 
+0

這是什麼代碼?在SSRS的某個地方? – SEarle1986

+0

你希望從這個查詢中看到什麼輸出? –

+0

代碼在sql server中。我想看到的輸出是月和年的下拉列表。例如2017年6月,2017年7月,2017年8月....從getdate() – Chairbedding

回答

0

有一些錯誤在你的代碼:

  1. 的DATEADD語法,正確dateadd(MONTH,1, @start)
  2. 您returnin克錯誤A SELECT statement that assigns a value to a variable must not be combined with data-retrieval operations.

嘗試這些代碼

DECLARE @start DATETIME = '2017-01-01' 
DECLARE @end DATETIME = Getdate(); 

WITH ctealldates 
    AS (SELECT @start startdate 
       ,@end enddate 
     FROM (VALUES (1))G(n) 
     UNION ALL 
     SELECT Dateadd(month, 1, startdate) startdate 
       ,enddate 
     FROM ctealldates 
     WHERE startdate < enddate) 
SELECT Datename(month, startdate) + ' ' 
       + Datename(year, startdate) MonthName, year(startdate) * 100 + month(startdate) OrderBy 
FROM ctealldates 
ORDER BY 
    year(startdate) * 100 + month(startdate) 
OPTION (maxrecursion 0); 



MonthName              OrderBy 
------------------------------------------------------------- ----------- 
January 2017             201701 
February 2017             201702 
March 2017             201703 
April 2017             201704 
May 2017              201705 
June 2017              201706 
July 2017              201707 
August 2017             201708 
September 2017            201709 
+0

到月份和年份沒有問題。請將 dateadd(day,1,startdate)startdate更改爲Dateadd(month,1,startdate)startdate,它會提高性能並刪除disitinct。 –

0

一個解決方案,我認爲將是如下。

  1. 創建一個存儲過程,如下

    declare @start DATE = '2011-05-01' 
    declare @end DATE = getdate() 
    ;with months (date) 
    AS 
    (
        SELECT @start 
        UNION ALL 
        SELECT DATEADD(month,1,date) 
        from months 
        where DATEADD(month,1,date)<[email protected] 
    ) 
    select Datename(month,date) As Months, Datename(year, date) As Years, CONCAT(Datename(month,date), ' ', Datename(year, date)) As MonthandYear from months 
    
  2. 創建報表RDL參數,以及可用值選項,可以選擇從查詢中獲取值。

enter image description here 選擇創建數據集從上面的查詢,在值字段中選擇MonthandYear字段和標籤爲「開始日期」。

當您運行報告時,您應該接收輸入參數作爲開始日期,並以開始日期和結束日期的日期差異值作爲下拉值。

希望這有助於。

+0

非常感謝您的幫助。您的查詢是正確的。 – Chairbedding