转到模板以连接切片中的查询

I want to concatenate my SQL query with UNION ALL and golang http://golang.org/pkg/text/template/

For example, I have:

var slice1 = []string{"2014-01-01", "2014-01-02", "2014-01-03"}
var slice2 = []string{"20140101", "20140102", "20140103"}

And query:

select {{.date}} as date, itemid, price
from orderhistory_t{{datetag}}

And using the template I want to create the query like the following:

select '2014-01-01' as date, itemid, price
from orderhistory_t20140101

union all 

select '2014-01-02' as date, itemid, price
from orderhistory_t20140102

union all 

select '2014-01-03' as date, itemid, price
from orderhistory_t20140103

How do I loop through the slice of Golang and put them in the sql template?

Thank you in advance!

I don't think template is the right tool for the job. Just create the query string and join it here is how:

http://play.golang.org/p/mM0mMfBZFK

package main

import (
    "fmt"
    "strings"
)

var slice1 = []string{"2014-01-01", "2014-01-02", "2014-01-03"}
var slice2 = []string{"20140101", "20140102", "20140103"}

func main() {
    var parts []string
    for i := 0; i < len(slice1); i++ {
        parts = append(parts, fmt.Sprintf("select %q as date, itemid, price from orderhistory_t%s", slice1[i], slice2[i]))
    }
    fmt.Println(strings.Join(parts, " union all "))
}

output:

select "2014-01-01" as date, itemid, price from orderhistory_t20140101 union all select "2014-01-02" as date, itemid, price from orderhistory_t20140102 union all select "2014-01-03" as date, itemid, price from orderhistory_t20140103