Skip to content

Commit 9bcfab0

Browse files
example for binding an array as a variable (#985)
third attempt to get this into the docs ;) co-authored by @sfc-gh-hachouraria
1 parent cd2078d commit 9bcfab0

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

doc/QueryingData.md

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -250,3 +250,37 @@ using (IDbConnection conn = new SnowflakeDbConnection())
250250
}
251251
```
252252

253+
Binding _an array_ As Variable
254+
------------------------------
255+
256+
Directly binding an array to a variable is not supported currently. Instead, the usual method to pass local arrays as SQL arrays via bind is to use the SQL form `PARSE_JSON(?)`, and then pass a JSON encoded array as string to the variable `?`
257+
258+
Using a stored procedure as an example, which can take an array as an input. Note, you'll need `Newtonsoft.Json` which is already a dependency of the driver.
259+
```cs
260+
using Snowflake.Data;
261+
using Newtonsoft.Json;
262+
..
263+
264+
using (IDbCommand cmd = conn.CreateCommand())
265+
{
266+
267+
int[] vals = new int[] { 1, 2, 3 };
268+
string array = JsonConvert.SerializeObject(vals); // alternatively you can do `vals.ToArray()` when passing it to `p1.Value`
269+
string sql = "CALL test_db.public.test(parse_json(?))"; // test SP, returns a single value
270+
// execute this sql with bind variable 'array'
271+
cmd.CommandText = sql;
272+
273+
var p1 = cmd.CreateParameter();
274+
p1.ParameterName = "1";
275+
p1.Value = array; // passing the array in the bind variable.
276+
p1.DbType = DbType.String;
277+
cmd.Parameters.Add(p1);
278+
279+
IDataReader reader = cmd.ExecuteReader();
280+
while (reader.Read())
281+
{
282+
Console.WriteLine(reader.GetString(0));
283+
}
284+
conn.Close();
285+
}
286+
```

0 commit comments

Comments
 (0)