Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SNOW-929914 Update README.md with example how to bind an array as variable #782

Closed
wants to merge 2 commits into from
Closed
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -642,6 +642,41 @@ using (IDbConnection conn = new SnowflakeDbConnection())
}
```

Binding _an array_ As Variable
------------------------------

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 `?`

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.
```cs
using Snowflake.Data;
using Newtonsoft.Json;
..

using (IDbCommand cmd = conn.CreateCommand())
{

int[] vals = new int[] { 1, 2, 3 };
string array = JsonConvert.SerializeObject(vals);
string sql = "CALL test_db.public.test(parse_json(?))"; // test SP, returns a single value
// execute this sql with bind variable 'array'
cmd.CommandText = sql;

var p1 = cmd.CreateParameter();
p1.ParameterName = "1";
p1.Value = array; // passing the array in the bind variable
Copy link
Collaborator

@sfc-gh-mhofman sfc-gh-mhofman Apr 8, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Simple array would do as well: https://github.com/snowflakedb/snowflake-connector-net/blob/master/Snowflake.Data.Tests/IntegrationTests/SFBindTestIT.cs#L567
Should we mention about it since it doesn't require dependency nor formatting to a JSON string?

p1.DbType = DbType.String;
cmd.Parameters.Add(p1);

IDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader.GetString(0));
}
conn.Close();
}
````

Close the Connection
--------------------

Expand Down
Loading