我正在尝试在SQL中执行以下操作:
创建一个名为usp_orders_by_dates的存储过程,显示之间发送的订单 特定日期。开始和结束日期将是存储过程的输入参数。
我的代码如下:
CREATE PROC usp_orders_by_dates @date DATETIME 如 BEGIN
SELECT
o.OrderID
,o.CustomerID
,c.CompanyName AS CustomerCompany
,s.ShipperID
,s.Company AS ShipperCompany
,@date AS ShippedDate
FROM Orders o
INNER JOIN Customer c
ON o.CustomerID = c.CustomerID
INNER JOIN Shippers s
ON o.ShipperID = s.ShipperID
ORDER BY
ShipperDate
END
如果我运行以下命令,我应该在ShippedDate中收到一个范围: EXEC usp_orders_by_dates'1991-07-01','1991-08-01'
答案 0 :(得分:1)
首先,您的Stored Procedure
缺少第二个EndDate
参数。
其次,您没有任何WHERE
条件可以过滤ShippedDate
CREATE PROCEDURE usp_orders_by_dates
@dateStart DATETIME,
@dateEnd DateTime
AS
SELECT
o.OrderID
,o.CustomerID
,c.CompanyName AS CustomerCompany
,s.ShipperID
,s.Company AS ShipperCompany
,@date AS ShippedDate
FROM Orders o
INNER JOIN Customer c
ON o.CustomerID = c.CustomerID
INNER JOIN Shippers s
ON o.ShipperID = s.ShipperID
WHERE ShipperDate BETWEEN @startDate AND @endDate
ORDER BY
ShipperDate
注意:你应该对BETWEEN非常小心,尤其是日期。如果您想搜索2013年1月1日至2013年12月31日(包括)之间的日期,则应使用WHERE BETWEEN '2013-01-01' AND '2014-01-01'
。使用WHERE Date >= '2013-01-01' AND Date < '2014-01-01'
会更好。前者将包括时间戳2014-01-01 00:00:00000
,后者将排除此。
答案 1 :(得分:1)
由于您的@dateEnd
参数可能是一个回合日期,而您的OrderDate列可能包含时间,因此请谨慎使用BETWEEN
或>= AND <=
结构。这些将仅包括该范围中最后一天午夜的订单,而不包括0:00:00.003之间的订单。 You should always use an open-ended range (and add a day to the end when necessary)
另外,在创建或引用对象时要非常小心不使用模式前缀。 This can lead to all kinds of hard-to-solve issues
最后,参数应为DATE
,以便任何时间都被截断,您不必担心部分天,因为有人决定使用GETDATE()
作为其中一个参数。
CREATE PROCEDURE dbo.usp_orders_by_dates
@dateStart DATE,
@dateEnd DATE
AS
BEGIN
SET NOCOUNT ON;
SELECT
o.OrderID
,o.CustomerID
,c.CompanyName AS CustomerCompany
,s.ShipperID
,s.Company AS ShipperCompany
,@date AS ShippedDate
FROM dbo.Orders AS o
INNER JOIN dbo.Customer AS c -- why is Orders plural, but not Customers?
ON o.CustomerID = c.CustomerID
INNER JOIN dbo.Shippers AS s -- Shippers is plural too. Inconsistent.
ON o.ShipperID = s.ShipperID
WHERE ShipperDate >= @startDate
AND ShipperDate < DATEADD(DAY, 1, @endDate)
ORDER BY
ShipperDate;
END
GO
答案 2 :(得分:0)
CREATE PROC usp_orders_by_dates
@startdate DATETIME,
@enddate DATETIME
AS BEGIN
SELECT
o.OrderID
,o.CustomerID
,c.CompanyName AS CustomerCompany
,s.ShipperID
,s.Company AS ShipperCompany
,s.ShippedDate
FROM Orders o
INNER JOIN Customer c
ON o.CustomerID = c.CustomerID
INNER JOIN Shippers s
ON o.ShipperID = s.ShipperID
WHERE s.shippeddate >= @startdate AND
s.shippeddate <= @enddate
ORDER BY
s.ShippedDate
END