2015-09-10 80 views
0

我正在嘗試使用變量爲我的開始日期和結束日期運行查詢。在查詢中使用變量作爲日期範圍

Declare @startshiptransdate as datetime 
Declare @endshiptransdate as datetime 

SET @StartShipTransDate = ISNULL(@StartShipTransDate, '08/30/2015') 
SET @EndShipTransDate = ISNULL(@EndShipTransDate, '09/05/2015') 

    (convert(date,co_ship.ship_date,101) >= @StartShipTransDate 
    AND convert(date,co_ship.ship_date, 101) <= @EndShipTransDate) 

當我運行這個時,我得到了大約200條記錄,我應該有什麼。

但是,如果我是這樣運行的:

(convert(date, co_ship.ship_date, 101) >= '08/30/2015' 
    AND convert(date, co_ship.ship_date, 101) <= '09/05/2015') 

我得到正確的記錄數。我相信這很簡單。

+2

能否請您粘貼整個查詢?您將零件排除在外,這使得難以排除故障。 – rwking

+0

當你將變量聲明爲日期而不是日期時,你是否得到相同的效果? –

+0

@EricHauenstein是的 – DragonRider

回答

0

有人要求我發佈查詢的其餘部分:

SET NOCOUNT ON; 
    Declare @startshiptransdate as datetime 
    Declare @endshiptransdate as datetime 


    SET @StartShipTransDate = IsNull(@StartShipTransDate, '08/30/2015') 
    SET @EndShipTransDate = ISNULL(@EndShipTransDate, '09/05/2015') 
    select 
     'O' as rectype, 
     ordercust.name as name, 
     ordercust.city as city, 
     ordercust.state as state, 
     ordercust.zip as zip, 
     co.cust_num as custnum, 
     shipcust.city As shipcity, 
     shipcust.state AS shipstate, 
     convert(varchar(10),co_ship.ship_date,101)as ShipDate, 
     item.item, 
     item.description, 
     co_ship.qty_shipped as Qtyshipped, 
     co_ship.cost as Cost, 
     co_ship.price AS price, 
     co_ship.co_line as OLN 

    from 
     co_ship 
      INNER JOIN coitem ON co_ship.co_num = coitem.co_num 
        AND co_ship.co_line = coitem.co_line 
        AND co_ship.co_release = coitem.co_release 
      INNER JOIN co ON co_ship.co_num = co.co_num 
      INNER JOIN custaddr shipcust ON co.cust_num = shipcust.cust_num 
        AND shipcust.cust_seq = co.cust_seq 
      Inner Join custaddr ordercust ON co.cust_num = ordercust.cust_num 
        AND ordercust.cust_seq = 0 
      INNER JOIN customer ON customer.cust_num = co.cust_num 
        AND customer.cust_seq = co.cust_seq 
      INNER JOIN item ON item.item = coitem.item 
    WHERE 
     (convert(date,co_ship.ship_date,101) >= @StartShipTransDate 
       AND convert(date,co_ship.ship_date, 101) <= @EndShipTransDate)