2017-05-09 125 views
1

我的代码不正确的语法附近“)” ......我不明白这一点

RETURNS TABLE 
AS 
RETURN 
(
with Documents as 
(
select TOP 100 PERCENT d.LeEn, d.Wacode, d.Waname, d.Arcode, d.Arname, sum(d.Quantity) as Quantity from Documents as d 
where (select max(DocumentDate) from Documents as d where d.DocumentCode = 'INW') <= d.DocumentDate 
group by d.LeEn, d.WarehouseCode, d.Waname, d.Arcode, d.Arname 
order by d.LeEn, d.WarehouseCode, d.Arcode 
) 
) 

和我得到这个

附近有语法错误)“。

有什么想法?

+2

用你正在使用的数据库标记你的问题。 –

回答

3

WITH应该在SELECT之前。在这种情况下,CTE似乎没有必要,所以才这样做:

RETURN (
select TOP 100 PERCENT d.LeEn, d.Wacode, d.Waname, d.Arcode, d.Arname, sum(d.Quantity) as Quantity 
from Documents as d 
where (select max(DocumentDate) 
     from Documents d 
     where d.DocumentCode = 'INW' 
     ) <= d.DocumentDate 
group by d.LeEn, d.WarehouseCode, d.Waname, d.Arcode, d.Arname 
order by d.LeEn, d.WarehouseCode, d.Arcode 
) 

ORDER BYTOP 100是完全多余的。 SQL Server不保证结果是有序的。

+0

我是否错过了解释“TOP 100 PERCENT”存在的微妙之处?这不是没有意义吗? –

+0

@Crowder同样的问题,如果我删除它... –

+1

@ T.J.Crowder。 。 。我把它放在里面.OP可能会认为结果将通过使用“TOP”来排序。这是不能保证的,但除了做一个不必要的排序(这是在'GROUP BY'之后,所以并没有那么糟糕),它没有任何害处。 –