0

I have a table in my database consisting of one column which is NewLanguage(varchar).I insert new languages to the table and i want to select the rows of the table and assign them to a string variable splitted by ','. I try to select the languages as in the code.

public string  SelectLanguagesFromDatabase()
    {

        NpgsqlCommand COM = new NpgsqlCommand(null,dbConnection);
        COM.CommandText = "select * from \"Languages\"";


    }

How can I select roes from database and assign them to string variable?

In an example

if Languages Column is

  NewLanguage

 C
 c++
 java

I want to have a a string as "C,c++,java". How can I do that ? Thanks.

2 Answers 2

2

You can use string_agg to concatenate all values from particular column in comma separated text like below:

SELECT string_agg (NewLanguage,',') FROM "Languages"
Sign up to request clarification or add additional context in comments.

2 Comments

@Ilesh Patel I updated my method then a i have another question which is what must be this method's return value?
if you store result into variable name like INTO var than it should be TEXT
0

Adapted from the user manual and using Ilesh Patel's query:

using System;
using System.Data;
using Npgsql;

public static class NpgsqlUserManual
{
  public static void Main(String[] args)
  {
    NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;Port=5432;User Id=joe;Password=secret;Database=joedata;");
    conn.Open();

    NpgsqlCommand command = new NpgsqlCommand("SELECT string_agg(NewLanguage,',') FROM Languages", conn);
    String results;

    try
    {
      results = (String)command.ExecuteScalar();
      Console.WriteLine("{0}", results);
    }


    finally
    {
      conn.Close();
    }
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.