带有日期参数的存储过程

时间:2013-03-17 06:44:30

标签: date stored-procedures parameters

我正在尝试创建一个在执行时具有日期参数的存储过程。我希望能够搜索特定日期之间发送的订单。我有这个:

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

3 个答案:

答案 0 :(得分:9)

where ShippedDate BETWEEN @startdate and @enddate

答案 1 :(得分: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
            }
        }

答案 2 :(得分:0)

"from" 和 "to" 是调用此函数时需要创建为输入的值。 函数的头没有显示在上面的 c# 代码中,应该是这样的: public HttpResponseMessage Get(string from, string to)