473,748 Members | 8,779 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 1812
[posted and mailed, please reply in news]

(er********@gma il.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****@sommarsk og.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_t o_table )? which I did but then when I tried to do:

SELECT ...
FROM tblTask
WHERE ...
AND intAssignedTo IN
(iter_intlist_t o_table(@strAss ignedTo))

I got an error saying that the function "iter_intlist_t o_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********@gma il.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_t o_table )? which I did but then when I tried to do:

SELECT ...
FROM tblTask
WHERE ...
AND intAssignedTo IN
(iter_intlist_t o_table(@strAss ignedTo))

I got an error saying that the function "iter_intlist_t o_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_nam es_iter @ids varchar(50) AS
SELECT P.ProductName, P.ProductID
FROM Northwind..Prod ucts 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****@sommarsk og.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
misunderstandin g 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,89 6');
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_strin g
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
2513
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 likely out of the question for now. Has someone done a more efficient minidom replacement module that we can just drop in? Preferrably written in C?
4
10190
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 (Len(txtAlbum.Value) < 1) Then MsgBox("Album Title cannot be empty") txtAlbum.SetFocus End If
3
6181
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 Procedures. For example, I have a form with the unbound controls startDate and endDate. When users click buttons, the dates change and a subform is populated. In DAO/MDB I just requery the subform. How can I do this in a Stored Procedure. I can't...
2
3148
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 procedures. It is enabled for SQL stored procedures. It is possible to "Build" and "Run" the Java SPs, it just isn't possible to click on the "Build for Debug" option. Thanks for any help in advance. Michael
3
2214
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 parameter... this: WHERE last_name LIKE '%' + @search_text + '%' seems does NOT work..
4
5160
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 need to create a stored procedure and return rows …and the empID I should give as an input parameter ..can u tell me how to write this in stored proc ?? Create or replace procedure emptest ( EID IN VARCHAR2, O_RESULT_SET OUT CURSOR_TYPE
6
1532
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 button(ProcPaymBTM_Click) on the web page(Detail View) on clicking this button all selected (checked) data needs to be stored temperorily and displayed on another page (Review Data) In this page i click confirm payment button to insert selected data to the...
2
2261
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 mulitple -pages based on the records. 3. passing an resultset as an input to a oracle procedure.
3
964
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 character of the id,which is the primary key or identifier.The database is MS SQL Server 2005 on a linux platform.Can anyone kindly help in to write the script I need such that I anyone can search online by id from our website and the deplaced...
3
5120
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 system. But my stored procedure also inserts and accesses a table in the database. Here's what I have it boiled down to: So, when I have
0
8989
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8828
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9537
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9367
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9243
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6073
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4869
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3309
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 we have to send another system
3
2213
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 can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.