2013-03-17 125 views
3

我正試圖創建一個存儲過程,該存儲過程在執行時具有日期參數。我希望能夠搜索特定日期之間發貨的訂單。我有這樣的:帶日期參數的存儲過程

create procedure sp_orders_by_dates 
     @startdate smalldatetime, 
     @enddate smalldatetime 
as 
select OrderID, 
     o.CustomerID, 

     c.CompanyName as CustomerCompany, 
     s.ShipperID, 
     s.CompanyName as ShipperCompany, 
     ShippedDate 

from Orders o join Customers c 
on  o.CustomerID = c.CustomerID join Shippers s 
on  s.ShipperID = o.ShipperID 
where @startdate = ShippedDate, 
     @enddate = ShippedDate 
order by ShippedDate 

和執行,我一定要做到這樣:

EXEC sp_orders_by_dates '1991-07-01', '1991-08-31' 

我知道這部分是出了什麼問題,但我只是無法弄清楚如何使「 「在這裏的講話之間:

where @startdate = ShippedDate, 
     @enddate = ShippedDate 
+0

備註:您應該**不要**爲存儲過程使用'sp_'前綴。微軟已經保留了這個前綴以供自己使用(參見*命名存儲過程*)](http://msdn.microsoft.com/en-us/library/ms190669%28v=sql.105%29.aspx),以及你將來有可能冒着名字衝突的風險。 [這對你的存儲過程性能也不好](http://sqlserverpedia.com/blog/sql-server-bloggers/stored-procedure-performance-using-%E2%80%9Csp_%E2%80%9D-prefix- %E2%80%93-神話或-事實/)。最好只是簡單地避免使用'sp_'並將其他內容用作前綴 - 或者根本沒有前綴! – 2013-03-17 08:51:25

回答

8
where ShippedDate BETWEEN @startdate and @enddate 
+0

很容易:-S – user2104163 2013-03-17 07:00:10

3

下面是在C#中搶:

DataTable t = new DataTable(); 
//set up your connectionString beforhand 
using(SqlConnection cn = new SqlConnection(conn)) 
     { 
      //and isolating the work from everything else 
      try 
      { 
       //configure the query apparatus, using the stored procedure 
       SqlCommand cmd = new SqlCommand(); 
       cmd.Connection = cn; 
       cmd.CommandType = CommandType.StoredProcedure; 
       cmd.CommandText = "<StoredProcName>"; 

       //set up the parameters 
       SqlParameter prmFrom = cmd.CreateParameter(); 
       prmFrom.Direction = ParameterDirection.Input; 
       prmFrom.ParameterName = "@FromDate"; 
       prmFrom.IsNullable = true; 
       SqlParameter prmTo = cmd.CreateParameter(); 
       prmTo.Direction = ParameterDirection.Input; 
       prmTo.ParameterName = "@ToDate"; 
       prmTo.IsNullable = true; 

       prmFrom.DbType = DbType.DateTime; 
       prmFrom.SqlValue = from; 

       prmTo.DbType = DbType.DateTime; 
       prmTo.SqlValue = to; 

       //make sure the command and the params go together from the app 
       cmd.Parameters.Add(prmFrom); 
       cmd.Parameters.Add(prmTo); 
       SqlDataAdapter da = new SqlDataAdapter(cmd); 

       //finally, fill the table so you can pass it back to the app 
       da.Fill(t); 
      } 
      catch(Exception ex) 
      { 
       //error handling goes here 
      } 
     }