How to convert columns data in comma separated list

折月煮酒 提交于 2019-12-06 16:49:36
shh
declare @table table
(
   PID integer,
   Medicine varchar(10)  )

insert into @table values (1, 'ABC')
insert into @table values (2, 'ABC')
insert into @table values (1, 'DEF')
insert into @table values (2, 'DEF')
insert into @table values (1, 'GHI')



SELECT DISTINCT a.PID,
                Medicine = STUFF((SELECT ',' + b.Medicine
                                    FROM @table b
                                    WHERE a.PID = b.PID
                                      FOR XML Path('')),1,1,'')
FROM @table a

RESULT:

**PID   Medicine**
1   ABC,DEF,GHI
2   ABC,DEF

I ended up creating following function by connecting to Data Dictionary but I got the error.

CREATE FUNCTION GetReport_Meds
   ( 
   PID varchar(15)
   )
   RETURNS String
BEGIN
DECLARE Meds String;
DECLARE CurMeds cursor AS SELECT  med_code from medication where patient = 
TRIM(PID) and end_date is null;
Meds = "";
OPEN CurMeds;
WHILE FETCH CurMeds DO
Meds = TRIM(Meds)+TRIM(CurMeds.med_code)+",";
END WHILE;
CLOSE CurMeds;
RETURN LEFT(Meds,LEN(Meds)-1);
END;
 poQuery: Error 7200:  AQE Error:  State = HY000;   NativeError = 5054;
  [iAnywhere Solutions][Advantage SQL][ASA] Error 5054:  The command cannot
 be completed with the current user permissions.  Cannot 
create function object in the data dictionary.

I have requested the company who created this db/app to add this function in the db so I can use it, lets see where I land.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!