Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
687 views
in Technique[技术] by (71.8m points)

select into - Building a comma-separated list of values in an Oracle SQL statement

I'm trying to build a comma-separated list of values out of a field in Oracle.

I find some sample code that does this:

DECLARE @List VARCHAR(5000)
SELECT @List = COALESCE(@List + ', ' + Display, Display)
FROM TestTable
Order By Display

But when I try that I always get an error about the FROM keyword not being were it was expected. I can use SELECT INTO and it works but if I have more than one row I get the fetch error.

Why can't I do as follows:

SELECT myVar = Field1
FROM myTable
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In Oracle, you would use one of the many string aggregation techniques collected by Tim Hall on this page.

If you are using 11.2,

SELECT LISTAGG(display, ',') WITHIN GROUP (ORDER BY display) AS employees
  INTO l_list
  FROM TestTable

In earlier versions, my preference would be to use the user-defined aggregate function approach (Tim's is called string_agg) to do

SELECT string_agg( display )
  INTO l_list
  FROM TestTable

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...