Hi guys I have a MSSQL stored procedure that I am converting to Plpgsql and it is acting very strange. When I add an ORDER BY clause to the query I get 1000s of rows with the "ID" I passed to the function as the first column and all the other columns are null. Here is the plpgsql function that I have written.

Code:
-- Gets all active users for specified users account

-- Use in TCBaseClass only

CREATE OR REPLACE FUNCTION Account_GetUsers_UserBranchFirst(int, int)

RETURNS TABLE(UserID int, 

    UserNameRev text, 

    UserName text, 

    BranchID bigint, 

    Email character varying)

AS 

$$

DECLARE BrID int;

BEGIN

SELECT 

    BranchID INTO BrID 

FROM 

    tblUser 

WHERE 

    UserID = $2;



RETURN QUERY 



SELECT 

    UserID, 

    UserNameRev, 

    UserName, 

    BranchID, 

    Email



FROM 

    viewUser 



WHERE 

    AccountID = $1 AND 

    DateDeleted IS NULL 



ORDER BY 

    CASE WHEN BranchID = BrID THEN 1 ELSE -1 END DESC, 

    UserNameRev;

END;

$$Language 'plpgsql';
So this function is almost exact to the MSSQL stored proc. I think there is a better way to do this in Plpgsql but I am not sure how. What it is trying to do is get the list of users and order the list so that the users in the same branch as the user passed to the function are at the top of the list.
If anyone can see an easier way to do this that will work please let me know.


Here is the MSSQL Stored Procedure.

Code:
-- Gets all active users for specified users account

-- Use in TCBaseClass only

CREATE PROCEDURE dbo.Account_GetUsers_UserBranchFirst

(

    @AccountID int, 

    @UserID int

)



AS 



DECLARE @BranchID int



SELECT 

    @BranchID = BranchID 

FROM 

    tblUser 

WHERE 

    UserID = @UserID 



SELECT 

    UserID, 

    UserNameRev, 

    UserName, 

    BranchID, 

    Email



FROM 

    viewUser 



WHERE 

    AccountID = @AccountID AND 

    DateDeleted IS NULL 



ORDER BY 

    CASE WHEN BranchID = @BranchID THEN 1 ELSE -1 END DESC, 

    UserNameRev

GO

Thanks
Liam