user1743160
user1743160

Reputation: 23

Concat database tables 1 field multiple records string in one row

I have a tables and records like :

EmployeeName
------------
Ram
Laxman
Bharat
Shatrugn

where i want to output to concat all values in one row in a single query:

I want result like:

Ram,Laxman,bharat,shatrugn

Concat string with ,(comma) in singlee line.. but i don't know that how to concat in android using cursor...

Upvotes: 1

Views: 766

Answers (3)

mukesh
mukesh

Reputation: 4140

     String values;
       if (cursor.moveToFirst()) {
                do {

               values=values + cursor.getString(0)+",";

                } while (cursor.moveToNext());

remove last comma

if (values.length() > 0)
 {
    values= values.substring(0,values.length() - 1);    
  }

Upvotes: 2

Rauf
Rauf

Reputation: 620

Here is my code i used...hope it helps you.

 private SQLiteDatabase myDataBase;
 Cursor cursor;
 String S="";
 String myPath2 = yourDBpath + yourDBNAME;
 try{
 myDataBase = SQLiteDatabase.openDatabase(myPath2, null,SQLiteDatabase.OPEN_READWRITE);
 String sql="your query";
 cursor=myDataBase.rawQuery(sql, null);
if(cursor != null)
{
   while(cursor.moveToNext())
   {
    S=S.append(cursor.getString(0));
    }
}
  } 
}catch(Exception e){

        }finally{
        myDataBase.close();
        }

Final result will be there in String S.

Upvotes: 2

Taryn
Taryn

Reputation: 247860

In SQLite, you can use GROUP_CONCAT():

select Group_Concat(EmployeeName)
from table1

See SQL Fiddle with Demo

If you had multiple fields that you want to return, then you would use a GROUP BY with the query, similar to this:

select id, Group_Concat(EmployeeName)
from table1
group by id

See SQL Fiddle with Demo

Upvotes: 4

Related Questions