Strangenut

SQL Server 2000/2005/2008 UDF to return a csv list of values from a query

Today I had to do a common task that I've done several times, but suddenly realized I should put up here, because its a fairly common issue.  Say you have TableA has a one to many relationship to TableB, and you want all of the values in TableB.dbo.ColumnA to be in a csv list based on the FK.  This is the perfect place for a simple UDF!

create function [dbo].[udf_ocrd_getProgList](@siteid nvarchar(17))
returns varchar(max)
with execute as caller
as
begin
      DECLARE @ProgTypes nvarchar(max)
      SELECT @ProgTypes = COALESCE(@ProgTypes + ', ', '') +
         CAST(np.progname AS nvarchar(65))
        from ocrd.progsite ps
       inner join ocrd.nprograms np on ps.programid = np.programid
       inner join ocrd.sites sites on sites.siteid = ps.siteidlnk
       where ps.siteidlnk = @siteid
      return (@ProgTypes)
end

and then to execute it...

select sitename, dbo.udf_getProgList(siteid)
  from ocrd.sites
 where siteid = '20030626152018383'

And it will return "Site Name Here", "Value 1, Value 2, Value 3"


Posted Jun 11 2009, 01:22 PM by dacrowlah
Powered by Community Server (Non-Commercial Edition), by Telligent Systems