2012-12-19 37 views
2

我創建一個具有代碼在它下面(部分)標量值功能:比較類型時在SQL函數

declare @start_time22 time(7); 
select @start_time22=Courses.[Course start time] from Courses where [Course ID][email protected] and [Course days]='monday wednesday'; 

if(@start_time22 is not null) 
    begin 
     IF (@start_time not between @start_time22 and @end_time22) 
      BEGIN 
       SET @Result = 1 
      END 
     ELSE 
      BEGIN 
       SET @Result = 0 
      END 
     IF (@end_time not between @start_time22 and @end_time22) 
      BEGIN 
       SET @Result = 1 
      END 
     ELSE 
      BEGIN 
       SET @Result = 0 
      END 
    end 
else 
    begin 
     set @Result = 5 
    end 


RETURN @Result 

函數總是返回值「 「,所以我想知道如果我可以比較類型時間在第一個地方... 或有什麼問題,我的代碼?

+4

'[課程天] ='週一wednesday''看起來很腥 – Andomar

+0

@Andomar檢查了...不是問題! –

+1

你在哪裏聲明@ endtime22? – Luv

回答

1

想必你想要的查詢是:

select @start_time22=Courses.[Course start time] 
from Courses 
where [Course ID][email protected] and [Course days] in ('monday', 'wednesday'); 

由於意見基本解釋,當你聲明一個變量,則該值設置爲NULL。如果你想將它設置爲其他值,則可以使用語法如:

declare @str varchar(255) = 'My favorite string' 

因爲查詢返回的結果,那麼變量從未被分配一個值。它仍然是一個NULL值。

此外,您還可以做在查詢本身的工作,在select使用case邏輯,而不是使用一個變量,然後做if邏輯:

select @result = (case when <whatever . . .) 
from Courses 
where [Course ID][email protected] and [Course days] in ('monday', 'wednesday'); 
+0

我測試了select語句,它返回一個像它應該的時間值,但只在特定情況下..這就是爲什麼我在if語句中使用'@ start_time22 is not null',事情是它總是去else,並返回一個'5'作爲結果!!!!!! –

+0

定義變量時,默認值爲5。 。 。 'set @Result = 5; <在這裏查詢>'。如果查詢未設置該值,則它保持在5。 –