【发布时间】:2019-03-02 15:24:05
【问题描述】:
餐桌顺序
OrderID | FromDate | ToDate
4523691 | 2015-01-23 | 2015-04-22
4523692 | 2015-05-07 | 2015-06-23
4523693 | 2015-02-09 | 2015-05-08
判断结果
| OrderID | Year | Month | Days |
| 4523691 | 2015 | 1 | 9 |
| 4523691 | 2015 | 2 | 28 |
| 4523691 | 2015 | 3 | 31 |
| 4523691 | 2015 | 4 | 22 |
| 4523692 | 2015 | 5 | 25 |
| 4523692 | 2015 | 6 | 23 |
| 4523693 | 2015 | 2 | 20 |
| 4523693 | 2015 | 3 | 31 |
| 4523693 | 2015 | 4 | 30 |
| 4523693 | 2015 | 5 | 8 |
如果使用每个 OrderID 的 where 语句运行脚本,则该脚本正在运行。所以这就是我需要帮助的,在没有订单 ID 限制的情况下运行查询。删除限制将导致以下错误 = Msg 512, Level 16, State 1, Line 5 子查询返回超过 1 个值。当子查询跟随 =、!=、、>= 或子查询用作表达式时,这是不允许的。
DECLARE @FromDate as datetime
DECLARE @Todate as date
DECLARE @Month as date
SET @FromDate = (select fromdate from Order where orderid = '4523693')
SET @ToDate = (select todate from Order where orderid = '4523693')
SET @Month = @FromDate
WHILE (eomonth(@Month) <= eomonth(@ToDate))
BEGIN
SELECT
OrderID
,year(dateadd(month, 0, eomonth(@Month)))
,month(dateadd(month, 0, eomonth(@Month)))
,case
when eomonth(@Month) = eomonth(fromdate) then datediff(d, fromdate, eomonth(fromdate))+1
when eomonth(@Month) = eomonth(todate) then datediff(day,DATEADD(m, DATEDIFF(m, 0, todate), 0) , todate)+1
else DATEPART(dd, DATEADD(dd, DATEPART(dd, DATEADD(mm, 1, dateadd(month, 0, eomonth(@Month)))) * -1, DATEADD(mm, 1, dateadd(month, 0, eomonth(@Month)))))
end as 'Days'
FROM Order
WHERE dateadd(month, 0, eomonth(fromdate)) <= eomonth(todate)
AND FROMDATE IS NOT NULL
AND ORDERID = '4523693'
SET @Month = dateadd(month, 1, eomonth(@Month))
END
【问题讨论】:
-
从您发布的代码中,我可以看到发生这种情况的唯一地方是您设置“开始”和“结束”日期的位置。但我会问你为什么要循环执行此操作?这应该是一个单一的查询。此外,避免使用“Order”等保留字作为对象名称。工作很痛苦。
-
不要为此使用循环。
标签: sql-server while-loop