String formatting using LISTAGG in Oracle. Escaping single quote ` ' `

試著忘記壹切 提交于 2019-12-11 06:58:30

问题


How can I format the output of listagg in Oracle to produce output(every field in the single quote) as 'student1', 'student2', 'student3'.
I have gone through documentation and other question on listagg but can't find much. SQL Query to concatenate column values from multiple rows in Oracle

SELECT LISTAGG(student_name,',')  WITHIN GROUP (ORDER BY student_name)
from students

Thanks


回答1:


You could use:

SELECT LISTAGG('''' || student_name || '''',',') 
       WITHIN GROUP (ORDER BY student_name)
FROM students;

or using ENQUOTE_LITERAL function:

SELECT LISTAGG(DBMS_ASSERT.ENQUOTE_LITERAL(student_name),',') 
       WITHIN GROUP (ORDER BY student_name) AS r
FROM students;

DBFiddle Demo




回答2:


This should do the job. You need to escape the ' in the query.

SELECT LISTAGG('''' || student_name || '''',', ') WITHIN GROUP (ORDER BY student_name)
FROM students


来源:https://stackoverflow.com/questions/48266756/string-formatting-using-listagg-in-oracle-escaping-single-quote

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