Ed Sinek
Ed Sinek

Reputation: 4987

SQL: retrieving CSV from within a View using a Function

I started off with the answer to this question.

I decided I wanted to retrieve the information (users, CSV roles for each user) from a view. The view didn't like the syntax of the WITH/FOR XML and so I decided to put that piece in a Function.

The view looks something like this:

SELECT u.UserId, u.UserName, dbo.GetRolesCsvFromUserId(u.UserId)
FROM Users u

I was successful up to the point of removing the trailing comma. Here's the function. How do i remove the trailing comma from within this function?

CREATE FUNCTION [dbo].[GetRolesCsvFromUserId] (@UserId int)
RETURNS nvarchar(100) AS
BEGIN
    RETURN
    (
        SELECT r.RoleName + ',' AS 'data()'
        FROM Roles r INNER JOIN UsersInRoles ur ON ur.RoleId = r.RoleId
        WHERE ur.UserId = @UserId FOR XML PATH('')
    )
END

Upvotes: 0

Views: 149

Answers (1)

Lamak
Lamak

Reputation: 70668

As @OMG Ponies pointed out, his solution solves your problem without needing a function. Still, if you need to create a function, you can do it without the XML PATH. Try this:

CREATE FUNCTION [dbo].[GetRolesCsvFromUserId] (@UserId int)
RETURNS nvarchar(100) AS
BEGIN
    DECLARE @Return nvarchar(100)
    SET @Return = ''

    SELECT @Return = @Return + r.RoleName + ','
    FROM Roles r INNER JOIN UsersInRoles ur ON ur.RoleId = r.RoleId
    WHERE ur.UserId = @UserId

    SET @Return = LEFT(@Return,LEN(@Return)-1)

    RETURN
    (
        @Return
    )
END

Upvotes: 1

Related Questions