Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass List in sql query

Tags:

java

sql

I have of values (1, 2, 3, for example), and I want to pass that list to a SQL query:

"select name from tbl where id in" + list 

How might I achieve this?

like image 314
n92 Avatar asked Aug 17 '11 16:08

n92


People also ask

How do you add a list to a query?

To create a list query from the selected column, right-click on the column and select 'Add as New Query' option as shown in the picture below. NOTE: You can also use Table. ToList() function in Power Query (M) language for creating a list from a data table.

Can we pass list in SQL query?

All you have to do is build the comma separated list of items and insert it in the string.

How do you pass a list of functions in SQL?

CREATE FUNCTION dbo. SplitInts ( @List VARCHAR(MAX), @Delimiter VARCHAR(255) ) RETURNS TABLE AS RETURN ( SELECT Item = CONVERT(INT, Item) FROM ( SELECT Item = x.i.value('(./text())[1]', 'varchar(max)') FROM ( SELECT [XML] = CONVERT(XML, '<i>' + REPLACE(@List, @Delimiter, '</i><i>') + '</i>'). query('.


2 Answers

you have to put your list directly to sql statement

example:

String sql="select name from tbl where id in ("+StringUtils.join(list, ',')+")";
Statement st=connection.createStatement();
st.execute(sql);
like image 70
corsair Avatar answered Sep 17 '22 17:09

corsair


I see in your reply to a comment that you're using HQL. If that's the case, the Hibernate folks make this one easy for you, in the query, just specify:

where id in (:ids)

and then use setParameterList("ids", list) passing your list. Hibernate will do all the expansion for you!

like image 33
Hoons Avatar answered Sep 17 '22 17:09

Hoons