alionthego
alionthego

Reputation: 9773

Using VTL Velocity, how can I create VALUES array to use in SQL Statement

I am trying to create an SQL Statement in my AWS resolver which uses Values.

For example:

#set( $inserts = [] )
#foreach ( $item in $ctx.args.input.listItems)
        $util.qr($inserts.add( ['$item.item_id', '$item.item_name', 'item.item_image_id'] ))
#end

And my SQL Statement is:

#set( $sql = "INSERT INTO items (item_id, item_name, item_image_id) VALUES $inserts" )

However this is not working. I there another way to create this type of SQL Statement? Thanks

Upvotes: 0

Views: 616

Answers (1)

Pedro Arantes
Pedro Arantes

Reputation: 5379

I'd do this way:

#set( $sql = "INSERT INTO items (item_id, item_name, item_image_id) VALUES " )
#foreach ( $item in $ctx.args.input.listItems)
    #set( $sql = $sql + "($item.item_id, $item.item_name, $item.item_image_id)")
    #if( $foreach.hasNext )
        #set( $sql = $sql + ", ")
    #else
        #set( $sql = $sql + ";")
    #end
#end
$sql

Do this solutions work for you?

Considering $ctx as

{
    ctx: {
        args: {
            input: {
                listItems: [
                    {
                        item_id: "itemId1",
                        item_name: "itemName1",
                        item_image_id: "itemImageId1"

                    },
                    {
                        item_id: "itemId2",
                        item_name: "itemName2",
                        item_image_id: "itemImageId2"

                    }
                ]
            }
        }
    }
}

the output is equals to INSERT INTO items (item_id, item_name, item_image_id) VALUES (itemId1, itemName1, itemImageId1), (itemId2, itemName2, itemImageId2);.

Upvotes: 2

Related Questions