我正在使用SQL Server 2012
并且我有以下T-SQL
查询。但是,它在执行时给出了一条错误消息。
错误消息是:
Msg 1014, Level 15, State 1, Line 2
A TOP or FETCH clause contains an invalid value.
我的T-SQL
查询如下:
;WITH N(N)AS
(SELECT 1 FROM(VALUES(1),(1),(1),(1),(1),(1),(1),(1),(1),(1))M(N)),
tally(N)AS(SELECT 1 FROM N,N a,N b,N c,N d)
INSERT INTO Allot4
SELECT
b.Date as [TDate],
Season,
RN,
TAProfileID,
TOName,
Market,
RoomType,
Property,
TOType
FROM Allot3 a
CROSS APPLY
(
SELECT top(datediff(d,Datefrom,case when DateTo >= DateFrom
then dateadd(d, 1, DateTo) else DateFrom end))
DATEADD(d,row_number()over(order by 1/0)-1, DateFrom) Date
FROM tally
) b
这里有什么问题,如何解决?
答案 0 :(得分:3)
当我们在TOP
子句中指定表达式时,我们必须确保在计算时表达式不应返回NULL
。我在你的陈述中添加了ISNULL
-
;WITH N(N)AS
(SELECT 1 FROM(VALUES(1),(1),(1),(1),(1),(1),(1),(1),(1),(1))M(N)),
tally(N)AS(SELECT 1 FROM N,N a,N b,N c,N d)
INSERT INTO Allot4
SELECT
b.Date as [TDate],
Season,
RN,
TAProfileID,
TOName,
Market,
RoomType,
Property,
TOType
FROM Allot3 a
CROSS APPLY
(
SELECT top(isnull(datediff(d,Datefrom,case when DateTo >= DateFrom
then dateadd(d, 1, DateTo) else DateFrom end)),0)
DATEADD(d,row_number()over(order by 1/0)-1, DateFrom) Date
FROM tally
) b
我们可以阅读更多关于TOP
条款的内容 -
https://docs.microsoft.com/en-us/sql/t-sql/queries/top-transact-sql