Home > Enterprise >  How to return all rows from a map interface
How to return all rows from a map interface

Time:09-02

Basically, I want to return all rows of a specific value in the query which looks as the following

var listOf []map[string]interface{}

query2 = strings.Replace(query2, "listOfIds", fmt.Sprintf("%v", listOf[0]["itemIds"]), -1)

at the moment the above returns first row as expected since listOf[0] but how can I return all of them, is there a way to do this?

EDIT:

To give a bit more context, there are 2 queries. Query 1 generates the ids which then are being past on query 2

whereQuery := " WHERE ssItemStoreId = itemIds AND ssItemStoreId = clId"   whereVariables   " AND itemClosedReason != 'Duplicated' AND clId != '' AND ItemArchived = 0"

query1 = query1   whereQuery

//Data Variables
var listOf []map[string]interface{}
        

The results are being passed on s.makeSqlQuery(query1, &listOf) which are being passed on query 2 but there are hundreds of rows and I am only retriving one. I tried using range but I get index out of range [0] with length 0

query2 = strings.Replace(query2, "listOfIds", fmt.Sprintf("%v", listOf[0]["itemIds"]), -1)

Thank you!

CodePudding user response:

To answer this question. provided context isn't enough.but i will add some answer.

You can iterate the "listOf" map and build separate query for each item and execute in db. Or iterate map and append "itemIds" in to query comman(,) separately and execute in db.

ex 1:

    //Your Way
var listOf []map[string]interface{}

listOf = append(listOf, map[string]interface{}{})

listOf[0]["1"] = "1"
listOf[0]["3"] = "3"

query2 := "select * from sometable where id= %s"
ids := ""
for _, v := range listOf {
    for _, v1 := range v {
        // replace logic
        if ids == "" {
            ids = fmt.Sprintf(`%v`, v1)
            continue
        }
        ids  = fmt.Sprintf(`,%v`, v1)
    }
}

query2 = fmt.Sprintf(query2, ids) // select * from sometable where id= 3,1
fmt.Println(query2)

ex 2:

 //  Easy Way
    listOf := make(map[string]interface{})

    listOf["1"] = "1"
    listOf["2"] = "2"

    query2 := "select * from sometable where id= %s"
    ids := ""
    for _, v := range listOf {
        // replace logic
        if ids == "" {
            ids = fmt.Sprintf(`%v`, v)
            continue
        }
        ids  = fmt.Sprintf(`,%v`, v)

    }

    query2 = fmt.Sprintf(query2, ids) // select * from sometable where id= 1,2

    fmt.Println(query2)
  •  Tags:  
  • go
  • Related