2

Is there a way to deal with apostrophes/multiples quotes in a SQL oracle string? I tried with listagg but only able to add the commas but not the apostrophes/multiples quotes. The goal is to add the users in another SQL Table -> IN Operator

Example:

select LISTAGG(username, ',') WITHIN GROUP (ORDER BY username) "USERNAME" from user

Current output: james, arthur, peter, gina, lehner

Goal: 'james', 'arthur', 'peter', 'gina', 'lehner'

Any suggestions?

Mureinik
  • 297,002
  • 52
  • 306
  • 350
James
  • 132
  • 12

3 Answers3

2

Try this

select LISTAGG(''''||username||'''', ',') WITHIN GROUP (ORDER BY username) "USERNAME" from user
gsalem
  • 1,957
  • 1
  • 8
  • 7
  • Thx you! for the explanation and support! – James Dec 27 '19 at 15:56
  • Perhaps the easiest way is to NOT build a list at all. Since the goal is to "add the users in another SQL Table -> IN, and that list must be built by a select. You are selecting user names in order to construct this list which will need to be de-constructed in the other query. Why not just incorporate the select that builds the list directly into the SQL -> IN. So Select Table ... where column_name in (Select username from user). – Belayer Dec 29 '19 at 04:30
2

You can apply any row-function (such as concatination) on the column before applying a window-function to it:

SELECT LISTAGG('''' || username || '''', ',') WITHIN GROUP (ORDER BY username) "USERNAME"
FROM   user
Mureinik
  • 297,002
  • 52
  • 306
  • 350
2

The simplest solution is to add the apostrophes in the delimiter and add a leading and trailing apostroph

 select ''''||listagg(username,q'[', ']') within group (order by username)||'''' as txt from names

gives

 'ames', 'arthur', 'gina', 'lehner', 'peter'
Marmite Bomber
  • 19,886
  • 4
  • 26
  • 53