較小的記錄我有ID和joiningdate列的表的員工,現在我想創建執行這樣的查詢:如何找到有結束日期比年份和月份
如果我通過月份和年份,然後所有的應顯示加入日期小於或等於此日期(月和年)的記錄。
如果月份爲空,則不應考慮月份,只應考慮年份。
較小的記錄我有ID和joiningdate列的表的員工,現在我想創建執行這樣的查詢:如何找到有結束日期比年份和月份
如果我通過月份和年份,然後所有的應顯示加入日期小於或等於此日期(月和年)的記錄。
如果月份爲空,則不應考慮月份,只應考慮年份。
SELECT * FROM YourTable WHERE TheDate <
DATEADD(MONTH, CAST(COALESCE(@MONTH,1) AS int) - 1,CAST(CAST(@YEAR as varchar(4)) + '0101' AS DATETIME));
DECLARE @tblTest AS TABLE
(
Name VARCHAR(50),
JoiningDate Date
)
INSERT INTO @tblTest
Values ('Sandip','11-Feb-2016')
,('Jigar','20-Jun-2016')
,('Milan','05-Jan-2015')
,('Suresh','25-Apr-2015')
Declare @Month VARCHAR(20)='Feb',@Year VARCHAR(4)='2015'
Declare @LastDateOfMonth Date
IF ISNULL(@Month,'')=''
BEGIN
SET @Month='DEC'
END
SET @LastDateOfMonth=DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, CAST('01-'+ @Month+'-'[email protected] AS DATE)) + 1, 0))
SELECT
*
FROM @tblTest
WHERE
JoiningDate<[email protected]
希望這有助於你:
Declare @yourtable table (EmpName varchar(10), JoiningDate datetime)
INSERT INTO @yourtable
Values ('A','10-Jan-2016')
,('B','20-Feb-2016')
,('C','05-Apr-2016')
,('D','31-Dec-2016')
Declare @month varchar(3) = ''
Declare @year varchar(4) = '2016'
select *
from @yourtable
Where (isnull(@month,'') <> '' and
(JoiningDate <= (SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,cast('01-'[email protected]+'-'[email protected] as date))+1,0)))))
or (isnull(@month,'') = '' and (Year(JoiningDate) = @year))
傳遞月份和年份INT格式或VARCHAR? –
datatype is varchar – Ashu
so mean month ='Jan'and year ='2016'right? –