You must Sign In to post a response.
  • Category: SQL Server

    Include row value in a string with single quotes

    I have to use table row values in a where condition as below.
    Row value should come in commas with single quotes


    Table structure

    Column1
    ABC
    Def
    Ghi
    Jkl

    Required query :

    Select * from Table2 where value in ('ABC','Def','Ghi','Jkl')
  • #768920
    Hai Lily,
    I am not sure why to construct the query like you have mentioned as this is the column values. If you want any kind of formatting, you can do in the code side.
    Get all the data in the table and then use the query from the front-end side.
    To do this,
    1. First get the records using the query:

    Select Column1 from Table1;

    2. Execute this query and get the results of the Column1.
    3. Now use the loop and make the data in comma separated values as:

    var sb= new StringBuilder();
    foreach(var val in Column1Collection)
    {
    sb.Append("'");
    sb.Append(val);
    sb.Append("'");
    sb.Append(",");
    }
    sb = sb.Remove(sb.Length-1,1); // to remove the last comma

    3. Now the sb will have the comma separated values.
    4. You can use the query and pass this values as:

    Select * from Table2 where Values in(sb);

    5. Execute this query.
    Hope it will be helpful to you.

    Regards,
    Pawan Awasthi(DNS MVM)
    +91 8123489140 (whatsApp), +60 14365 1476(Malaysia)
    pawansoftit@gmail.com


Sign In to post your comments