How to convert columns data in comma separated list

匿名 (未验证) 提交于 2019-12-03 09:06:55

问题:

I am in little strange situation. It is a third party application which from front end doesn't allow user procedures or udf/scalar functions to be called.

Only option is to write SQL and below is how my data looks. First pic has a mistake last PID was suppose to be 1 and second last 2.

What I need it to be is this,

This can be easily done using UDF/cursor in this Advantage Database Server 9 but I don't have a choice. I don't know if it is really possible. In Sybase there exist a function called list which does this sort of work very easily but not sure here.

Application does allow to call built in functions.

回答1:

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 


回答2:

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.



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