2015-09-23 131 views
0

我有一個三列的表 - 'DateFrom', 'DateTo' and 'Loc'。 我想寫程序,將採取三個參數 - '@From_', '@To_' and '@Loc_'然後檢查表是否有兩行,例如第一行'DateFrom'早於'@From_',並且'DateTo'例如第二行晚於'@To_ '和‘祿’是正確的,過程將返回1,如果不是返回0包含日期和檢查

例如我有行表:

+---------------------------+ 
| DateFrom DateTo Loc | 
+---------------------------+ 
| 2015-01-01 2015-01-03 1 | 
| 2015-01-04 2015-01-06 1 | 
+---------------------------+ 

,我將exec的使用參數@DateFrom_='2015-01-02', @DateTo_='2015-01-05',@Loc_=1過程,過程將返回1

但是如果表是:

+---------------------------+ 
| DateFrom DateTo Loc | 
+---------------------------+ 
| 2015-01-01 2015-01-03 1 | 
| 2015-01-05 2015-01-06 1 | 
+---------------------------+ 

過程使用相同的參數:@DateFrom_='2015-01-02', @DateTo_='2015-01-05',@Loc_=1將返回0,因爲2015-01-04不存在於表中。 請求幫助,謝謝。

+0

我有程序運作良好,如果有一行更正'Loc',我不知道如何執行將檢查許多行的過程,所以我希望StackOverFlow用戶可以幫助我。我不期望完成程序,但建議請。 –

回答

0

這樣?

declare @ct as int=0 

select @ct=count(*) from Table_name where DateFrom>@from_date and toDate<@to_date and [email protected] 

    if @ct>1 
    begin 
     select 1 
    end 
    else 
     begin 
     select 0 
     end 

編輯2:

declare @ct as int=0 
declare @dateDiff as int=0 

    select @ct=count(*),@dateDiff=datediff(Day,@from_date,@to_date) from Table_name where DateFrom>@from_date and toDate<@to_date and [email protected] 

     if @ct>1 and @[email protected] 
     begin 
      select 1 
     end 
     else 
      begin 
      select 0 
      end 

這個什麼?

+0

不幸的不是。我在那裏解釋了爲什麼添加了幾​​句話。如果在表格中,對於Loc = 1不是日期'2015-01-04',它位於@ DateFrom ='2015-01-01'和@ DateTo ='2015-01-06'之間,程序應返回0 –

+0

請參閱編輯2,@ user3271955 –

0

你可以嘗試這樣做。

SELECT TOP(1) (CASE WHEN DateFrom > @from_date AND toDate < @to_date AND loc = @loc THEN 1 ELSE 0 END) AS Result FROM table_name 
+0

請在回答中添加解釋,這不是一場比賽,也不是解決問題,而是回答問題。 – xpy

0

我有想法。

步驟1:

予取第一行,其中 'DateFrom' 是早於'@From_'。如果'DateTo'晚於'@To_'return 1

第2步:

否則總有一天會增加'@DatAUX = DateTo'並檢查是否有行,其中'DateFrom'是早於'@DatAUX',我採取「DateTo」與PARAM '@DateTo'比較。如果'DateTo'來自表是更晚,程序將return 1,否則重複step 2。'