2017-02-28 54 views
0

我使用這個方法來獲取數據: -而子句中使用狀態日期時間的SQL Server

declare @date varchar(30),@time varchar(20); 
set @date = REPLACE(CONVERT(varchar(10), getdate(), 102), '.', '-'); 
set @time = FORMAT(getdate(), 'HH:mm'); 

select j.JourneyID,j.Source 
     from journeytb j left join usertb u on j.userid = u.userid 
     left join TravelerTypeTB traveler on j.TravelerType = traveler.SrNo    
      where 
       j.UserID = @user_id 

       and j.StartDate >= (case when (@start_date is null) then @date when @start_date is not null then @start_date else @date end) 
       and j.StartTime >= (case when @start_time is null then @time when @start_time is not null then @start_time else @time end) 

我要檢查日期和時間可以說,我檢查當前的日期,如果是少比從表格列的日期那麼它是真實的和相同的情況下,時間問題在這裏是如果日期是在時間範圍內,那麼它的真,如果時間不是然後錯誤,這不會給表中的數據我想檢查日期那麼在此'AND'條款內的時間或者是他們的任何其他方式

+2

刪除了MySQL標籤,因爲它最有可能被添加到獲得關注。 –

+1

您可以添加一些示例數據和預期結果嗎? – HoneyBadger

+0

如果您添加一些示例數據和預期輸出,我們可以真正幫助您。 –

回答

0

這是怎麼回事?

and 
(
    (
    j.StartDate = (case when (@start_date is null) then @date when @start_date is not null then @start_date else @date end) 
    and j.StartTime >= (case when @start_time is null then @time when @start_time is not null then @start_time else @time end) 
    ) 
    or 
    j.StartDate > (case when (@start_date is null) then @date when @start_date is not null then @start_date else @date end 
) 
+0

謝謝這種方法可能會幫助我解決問題。 – rinki

2

如果您有日期和時間兩個獨立的價值觀,不能你更輕鬆地通過連接起來,放回單DATETIME格式,比較能夠解決呢?例如:

DECLARE @TABLE TABLE -- Example table with data 
(
    StartDate VARCHAR(10) 
    ,StartTime VARCHAR(5) 
); 

INSERT INTO @TABLE VALUES ('01/01/2017','10:15'); 
INSERT INTO @TABLE VALUES ('02/02/2017','11:25'); 
INSERT INTO @TABLE VALUES ('03/03/2017','15:05'); 
INSERT INTO @TABLE VALUES ('04/02/2017','06:00'); 

DECLARE @CURRENT AS DATETIME; 
SET @CURRENT = GETDATE(); -- The parameter you're checking against 

SELECT * 
FROM @TABLE 
WHERE CONVERT(DATETIME,StartDate + ' ' + StartTime) < @CURRENT -- Concatenated full DATETIME compared to the parameter 
; 

僅返回表中小於您檢查值​​的那些日期。

當然你可以玩這個來做很多不同的方式...

+0

謝謝你,這也像魅力 – rinki

+0

不客氣。很高興提供幫助。 – 3BK

+0

@rinki如果您不介意,您是否可以將回答標記爲答案,如果它對您有用?謝謝! – 3BK