473,508 Members | 2,428 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Help with "IN" in stored procedure.

I have a stored procedure which is performing a search against a "task"
table. I would like to pass in a variable called @strAssignedTo which
will be a comma delimeted list of employee ID's ie: "5,6,10". So my SQL
without this variable would be something like:

WHERE intAssignedTo IN (5,6,10)

but when I try to do:

WHERE intAssignedTo IN (@strAssignedTo)

I get an error saying "cannot convert strAssignedTo to an integer"

What's the proper way to do this? THANKS

Aug 2 '05 #1
4 1801
[posted and mailed, please reply in news]

(er********@gmail.com) writes:
I have a stored procedure which is performing a search against a "task"
table. I would like to pass in a variable called @strAssignedTo which
will be a comma delimeted list of employee ID's ie: "5,6,10". So my SQL
without this variable would be something like:

WHERE intAssignedTo IN (5,6,10)

but when I try to do:

WHERE intAssignedTo IN (@strAssignedTo)

I get an error saying "cannot convert strAssignedTo to an integer"


Which is because there is no macro expansion going on here. Keep in
mind that you can say things like

WHERE x IN (@a, @b, @c)

Hm, there is actually a macro expansion going on here, since the above
is internally rewritten to

WHERE x = @a OR x = @b OR x = @c

Anyway, for how to this, have a look at
http://www.sommarskog.se/arrays-in-s...st-of-integers.
--
Erland Sommarskog, SQL Server MVP, es****@sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Aug 2 '05 #2
Thanks for your reply but I couldnt make heads or tails of that
article. It looked like I needed to make a user defined function maybe?
(iter_intlist_to_table )? which I did but then when I tried to do:

SELECT ...
FROM tblTask
WHERE ...
AND intAssignedTo IN
(iter_intlist_to_table(@strAssignedTo))

I got an error saying that the function "iter_intlist_to_table" did not
exist. I'm fairly new to stored procedures and SQL in general so that
article was a bit over my head.

Aug 2 '05 #3
Erich93063 (er********@gmail.com) writes:
Thanks for your reply but I couldnt make heads or tails of that
article. It looked like I needed to make a user defined function maybe?
Yes, that is what the gist of. (There are other methods, but using a
UDF is the best.)
(iter_intlist_to_table )? which I did but then when I tried to do:

SELECT ...
FROM tblTask
WHERE ...
AND intAssignedTo IN
(iter_intlist_to_table(@strAssignedTo))

I got an error saying that the function "iter_intlist_to_table" did not
exist. I'm fairly new to stored procedures and SQL in general so that
article was a bit over my head.


Well, it is easier, if you mimick the example in the article, rather
than trying your own syntax. That's a table-valued function, and
you use a table-valued function just like you use a table. The example
uses JOIN, although in retrospect, I should probably have used EXISTS
instead:

CREATE PROCEDURE get_product_names_iter @ids varchar(50) AS
SELECT P.ProductName, P.ProductID
FROM Northwind..Products P
WHERE EXISTS (SELECT *
FROM iter_intlist_to_table(@ids) i
WHERE P.ProductID = i.number)
go

But that's a matter of style only.

Some parts of the article, for instance all the performance tests, are
certainly above novice level. But that is also why I gave a direct
link to a function and example on how to use it.

I suggest that you copy the function, and play with the example in
the article. No way is better to learn, than getting your hands on it
yourself. May take little longer for the actual task at hand, but next
time you need it, you know it better.
--
Erland Sommarskog, SQL Server MVP, es****@sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Aug 2 '05 #4
This is a common Newbie question. This shows that you don't know what
a scalar parameter is. This is MUCH worse than not knowing SQL. This
is a fundamental programming concept that you should learn in the first
week of any language class.

1) The dangerous, slow kludge is to use dynamic SQL and admit that any
random furure user is a better programmer than you are. It is used by
Newbies who do not understand SQL or even what a compiled language is.
A string is a string; it is a scalar value like any other parameter;
it is not code. This is not just an SQL problem; this is a basic
misunderstanding of programming of principles.

2) Passing a list of parmeters to a stored procedure can be done by
putting them into a string with a separator. I like to use the
traditional comma. Let's assume that you have a whole table full of
such parameter lists:

CREATE TABLE InputStrings
(keycol CHAR(10) NOT NULL PRIMARY KEY,
input_string VARCHAR(255) NOT NULL);

INSERT INTO InputStrings VALUES ('first', '12,34,567,896');
INSERT INTO InputStrings VALUES ('second', '312,534,997,896');
etc.

This will be the table that gets the outputs, in the form of the
original key column and one parameter per row.

CREATE TABLE Parmlist
(keycol CHAR(10) NOT NULL,
parm INTEGER NOT NULL);

It makes life easier if the lists in the input strings start and end
with a comma. You will need a table of sequential numbers -- a
standard SQL programming trick, Now, the query, in SQL-92 syntax
(translate into your local dialect):

INSERT INTO ParmList (keycol, parm)
SELECT keycol,
CAST (SUBSTRING (I1.input_string
FROM S1.seq
FOR MIN(S2.seq) - S1.seq -1)
AS INTEGER)
FROM InputStrings AS I1, Sequence AS S1, Sequence AS S2
WHERE SUBSTRING (',' || I1.input_string || ',' FROM S1.seq FOR 1) =
','
AND SUBSTRING (',' || I1.input_string || ',' FROM S2.seq FOR 1) =
','
AND S1.seq < S2.seq
GROUP BY I1.keycol, I1.input_string, S1.seq;

The S1 and S2 copies of Sequence are used to locate bracketing pairs of
commas, and the entire set of substrings located between them is
extracted and cast as integers in one non-procedural step. The trick
is to be sure that the right hand comma of the bracketing pair is the
closest one to the first comma.

You can then write:

SELECT *
FROM Foobar
WHERE x IN (SELECT parm FROM Parmlist WHERE key_col = :something);

Hey, I can write kludges with the best of them, but I don't. You need
to at the very least write a routine to clean out blanks and
non-numerics in the strings, take care of floating point and decimal
notation, etc. Basically, you must write part of a compiler in SQL.
Yeeeech! Or decide that you do not want to have data integrity, which
is what most Newbies do in practice.

3) The right way is to use tables with the IN () predicate, You set up
the procedure declaration with a "fake array", like this in SQL/PSM
(translate into your local dialect):

CREATE PROCEDURE Foobar ( <other parameters>, IN p1 INTEGER, IN p2
INTEGER, .. IN pN INTEGER) -- default missing values to NULLs
BEGIN
SELECT foo, bar, blah, yadda, ...
FROM Floob
WHERE my_col
IN (SELECT DISTINCT parm
FROM ( VALUES (p1), (p2), .., (pN))
AS ParmList(parm)
WHERE parm IS NOT NULL
AND <other conditions>)
AND <more predicates>;
<more code>;
END;

3) The right way! You load the Parmlist table with values so that each
value is validated by the SQL engine, subject to more constraints and
you have no SQL injection problems. A good optimizer will not need the
SELECT DISTINCT, just a SELECT.

Aug 3 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
2498
by: Paul Miller | last post by:
We've run into minidom's inabilty to handle large (20+MB) XML files, and need a replacement that can handle it. Unfortunately, we're pretty dependent on a DOM, so a pulldom or SAX replacement is...
4
10166
by: Corepaul | last post by:
I am a newbie using Access 2000. I am using the following test in the txtAlbum OnExit procedure to prevent leaving an empty text box for a required field If (IsNull(txtAlbum.Value)) Or...
3
6169
by: Lauren Quantrell | last post by:
I am feeling a little overwhelmed trying to get my MDB-ADP conversion going. The first thing I need to figure out (very quickly) is how to use the values of unbound controls of forms in Stored...
2
3130
by: Michael | last post by:
Running DB2 v7 UDB ("DB2 v7.1.0.93", "n031208" and "WR21333") on Windows XP, I am unable to find out why the "Build for Debug" option within Stored Procedure Builder is not enabled on Java stored...
3
2200
by: HotFrost | last post by:
Hello everyone, i wonder if someone can give me some idea how and what is the right way to use wild characters in stored procedures with parameters... Assuming that @searchs_text is the...
4
5141
by: roshnair | last post by:
Hi i have a small problem . I need to change one query to stored procedure and call it in my vb.net application.Query is : Select * from emp where empid in (‘001’,’002’) For this query I...
6
1524
by: svgeorge | last post by:
I need help in C Sharp Web Interface , I have web pages for making several 9 type of payments. The data gets loaded on web page from SQL server 2005 database. Then I have Process payment...
2
2227
by: adukuri | last post by:
Hi, I am new to jsp coding and I need some help in coding. 1. Writing to a text file from a result set. need to open a new txt file on a unix box and store it. 2. Paging. To generate...
3
956
by: Dataman123 | last post by:
Dear All! I'm not a good programmer,but need help: Scenario: I am loading a a pdf file containing a table of data ,(on the row you have id numbers,whilst on the columns you have attributes or...
3
5090
by: leesquare | last post by:
Hello, I need some help getting output values from my stored procedures when using adodbapi. There's an example testVariableReturningStoredProcedure in adodbapitest.py, and that works for my...
0
7405
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
7066
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
7504
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
5643
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
4724
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3214
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
1568
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
773
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
435
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.