Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there SQL parameter binding for arrays?

Tags:

Is there a standard way to bind arrays (of scalars) in a SQL query? I want to bind into an IN clause, like so:

SELECT * FROM junk WHERE junk.id IN (?); 

I happen to be using Perl::DBI which coerces parameters to scalars, so I end up with useless queries like:

SELECT * FROM junk WHERE junk.id IN ('ARRAY(0xdeadbeef)'); 

Clarification: I put the query in its own .sql file, so the string is already formed. Where the answers mention creating the query string dynamically I'd probably do a search and replace instead.

Edit: This question is kind of a duplicate of Parameterizing a SQL IN clause?. I originally thought that it should be closed as such, but it seems like it's accumulating some good Perl-specific info.

like image 957
cdleary Avatar asked Feb 04 '09 23:02

cdleary


People also ask

Can SQL handle arrays?

Conclusion. As you can see, SQL Server does not include arrays. But we can use table variables, temporary tables or the STRING_SPLIT function. However, the STRING_SPLIT function is new and can be used only on SQL Server 2016 or later versions.

What is parameter binding in SQL?

Bind parameters—also called dynamic parameters or bind variables—are an alternative way to pass data to the database. Instead of putting the values directly into the SQL statement, you just use a placeholder like ? , :name or @name and provide the actual values using a separate API call.

What is bind array Oracle?

Using the Oracle array binding feature can greatly speed up execution of the application when inserting or updating big volumes of data. The main advantage is that array binding allows you to execute several INSERT SQL statements with the different parameters for the one time.

What bound parameters?

Statement parameters are special tokens that are inserted into the SQL command string before it is passed to one of the sqlite3_prepare_xxx() functions. They act as a placeholder for any literal value, such as a bare number or a single quote string.


1 Answers

If you don't like the map there, you can use the 'x' operator:

my $params = join ', ' => ('?') x @foo; my $sql    = "SELECT * FROM table WHERE id IN ($params)"; my $sth    = $dbh->prepare( $sql ); $sth->execute( @foo ); 

The parentheses are needed around the '?' because that forces 'x' to be in list context.

Read "perldoc perlop" and search for 'Binary "x"' for more information (it's in the "Multiplicative Operators" section).

like image 54
Ovid Avatar answered Sep 20 '22 14:09

Ovid