开发者

ORDER BY clause vs function of SQL Server

I want to use ORDER BY clause in functions of SQL Server. But I cannot use this, it not allow that. So, how can I use this?

CREA开发者_StackOverflowTE FUNCTION PersonIDGet
    (

    )
RETURNS int
AS
BEGIN

    DECLARE @PersonID int;
        SET @PersonID = (SELECT PersonID FROM Person ORDER BY PersonID DESC);

        RETURN @PersonID

END

I got this error.

The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP or FOR XML is also specified.


You need to have top 1 in your select statement. You are fetching more than one row so SQL Server have trouble figuring out what PersonID will be assigned to @PersonID.

CREATE FUNCTION PersonIDGet
    (

    )
RETURNS int
AS
BEGIN
    DECLARE @PersonID int;
    SET @PersonID = (SELECT TOP 1 PersonID FROM Person ORDER BY PersonID DESC);
    RETURN @PersonID
END
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜