473,385 Members | 1,798 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

How to Passing Multi Value Parameter in SQL Query

I have a query :
Exec 'Select * From Receiving Where Code In (' + @pCode + ')'

@pCode will contain more than one string parameter, eg : A1, A2, A3

How can i write that parameters, I try use :
set @pCode='A1','A2','A3'
but get an error : Incorrect syntax near ','
Please help me

Thanks

Jul 23 '05 #1
10 125411
Resant, here is the answer.

1. set @pCode='''A1'',''A2'',''A3'''

2. Exec ('Select * From Receiving Where Code In (' + @pCode + ')')

Good luck.

source4book.com

http://www.source4book.com

Jul 23 '05 #2
Resant (re******@yahoo.com) writes:
I have a query :
Exec 'Select * From Receiving Where Code In (' + @pCode + ')'

@pCode will contain more than one string parameter, eg : A1, A2, A3

How can i write that parameters, I try use :
set @pCode='A1','A2','A3'
but get an error : Incorrect syntax near ','


EXEC without parentheses is a call to a stored procedure. Wrap the
expression in parathenses to get dynamic SQL:

EXEC(@sql)

But you should not use dynamic SQL for this sort of thing. Have a look
at http://www.sommarskog.se/arrays-in-s...ist-of-strings for
a much better way to approach this problem.
--
Erland Sommarskog, SQL Server MVP, es****@sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 23 '05 #3
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 PRIMARY KEY,
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 in single queries 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
AS
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>

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.

Jul 23 '05 #4
--CELKO--
I'm interested with method no.3 that use IN () predicate, but still
confused. Would you like to give an example please. That query is too
strange for me.

Thank you

Jul 23 '05 #5
Resant (re******@yahoo.com) writes:
--CELKO--
I'm interested with method no.3 that use IN () predicate, but still
confused. Would you like to give an example please. That query is too
strange for me.


You are not the only one. One would think that a person Joe Celko that
scorns other people for using proprietary features, would stay clear from
that himself, but oh no. That syntax exists in ANSI SQL, but that does
not mean that it works everywhere. Specifically, that syntax does not
work on SQL Server. As a general advice for new users, you do best in
ignore Celko's postings, as they are more likely to be confusing and
insulting than to be helpful.

Did you look at the link that I posted? That's a solution that does not
use IN, but it is one that is effecient on SQL Server.
ttp://www.sommarskog.se/arrays-in-sql.html#iter-list-of-strings.

--
Erland Sommarskog, SQL Server MVP, es****@sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 23 '05 #6
That is a "cut & paste" I use which is written in Standard SQL for a
lot of different newsgroups. The VALUES clause constructs a column or
a full table and the AS gives the table and its columns names to
reference. In SQL Server dialect, you would use:

(SELECT p1
UNION ALL
SELECT p2
UNION ALL
..
SELECT pN) AS Parmlist (parm)

Which I find to be much stranger since a SELECT must have a FROM in
Standard SQL and just about any other dialect. I have no idea why MS
has resisted row constructors in so many places in T-SQL when the
engine has the ability.

Jul 23 '05 #7
> Did you look at the link that I posted? That's a solution that does not
use IN, but it is one that is effecient on SQL Server.
ttp://www.sommarskog.se/arrays-in-sql.html#iter-list-of-strings.


Yes I did, it's more reasonable for me.
But if I intend to give access for user to the table that is accessed
in my stored procedure, it should be ok if I use dynamic sql as my
first posting, isn't it?

Thank you

Jul 23 '05 #8
Resant (re******@yahoo.com) writes:
Yes I did, it's more reasonable for me.
But if I intend to give access for user to the table that is accessed
in my stored procedure, it should be ok if I use dynamic sql as my
first posting, isn't it?


There are really no advantages with dynamic SQL for this kind of problem.
Of course, for smaller lists it does not matter. But if the lists are
very long, you get very poor performance with dynamic SQL.
--
Erland Sommarskog, SQL Server MVP, es****@sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 23 '05 #9
Hi,

Even I was looking for same and I found a great method to overcome your
problem. Trick is not to use IN clause and use the strings functions.


So the easiest way to think is wherever you write

( Column IN (@Params) )

you just replace above peice of code with

( CHARINDEX( QUOTENAME( Column , '''' ), @Params)<> -1 )

Background:

if you want to find out wheather "b" exists in a,b,c or not use this.

@Params = "a,b,c"

CHARINDEX( Column , @Params ) <> -1

this will turn on true if column has a , b or c in it.

here problem may araise if you have set like aa,ab,bc
and you are searching for only b which doesnt exist..

here you can quote your string like

@Params = "'a','b','c'"

and change sql command as

CHARINDEX( QUOTENAME( Column , '''' ) , @Params )<> -1

So the easiest way to think is wherever you write

( Column IN (@Params) )

you just replace above peice of code with

( CHARINDEX( QUOTENAME( Column , '''' ), @Params)<> -1 )

*** Sent via Developersdex http://www.developersdex.com ***
Aug 2 '05 #10
[posted and mailed, please reply in news]

Akash Kava (ac****@hotmail.com) writes:
Even I was looking for same and I found a great method to overcome your
problem. Trick is not to use IN clause and use the strings functions.

So the easiest way to think is wherever you write

( Column IN (@Params) )

you just replace above peice of code with

( CHARINDEX( QUOTENAME( Column , '''' ), @Params)<> -1 )
Background:

if you want to find out wheather "b" exists in a,b,c or not use this.

@Params = "a,b,c"

CHARINDEX( Column , @Params ) <> -1

this will turn on true if column has a , b or c in it.


Warning! This method have serious performance problems, even with
short lists. First of all any index on Column will not be used.
But even if the column is not indexed - in which case this does not
matter - this operation is very expensive. When I ran performance
tests a couple of years ago on various methods, a list that was
around 255 character long cause a search to take 40 seconds!

That test, as well as several other - and better! - methods to tackle
this problem is described in an article on my web site. See
http://www.sommarskog.se/arrays-in-sql.html.
--
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 #11

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

Similar topics

1
by: Michael DeLawter | last post by:
Using Access 2002. I have a chart in a report that is currently based on a query in which the user enters the start and end date for the chart to display. Both the start and end dates have been...
5
by: MX1 | last post by:
Simpler way to ask question from my previous post. I wrote a query and it has a paramter field in it. I want to enter a date with the current year. If it I put in 6/30/2003, it works great. If I...
3
by: MX1 | last post by:
I'm ready to pull the hair out of my head. I have a query with a couple of parameters that I want to get from combo boxes on a form. One parameter is a date with a dynamically calculated year and...
1
by: Yodel99 | last post by:
Greetings, I have a form (Form1) based on a parameter query (Query1). I want the value that the user enters in the parameter window to populate a field in the form. I've been able to use the...
1
by: carrionk | last post by:
Hi, I have created a Subform which SourceObject is a parameter query. This is the Query: Qry Name:80IsscomProduct SELECT * FROM Isscomp28 WHERE Like ;
2
by: dath | last post by:
Hi, Searched the forum and found a lot on passing form input to aquery but not the other way around. Here is the situation: I have a timesheet form based on a subform query that asks the...
12
by: dave_dp | last post by:
Hi, I have just started learning C++ language.. I've read much even tried to understand the way standard says but still can't get the grasp of that concept. When parameters are passed/returned...
5
by: Trevisc | last post by:
Happy Thursday Everyone, I am trying to create a parameter that is one long varchar but that will be used in a SQL statement IN function: //string queryString = GetCurrentTitles(); //Below is...
3
by: timleonard | last post by:
I use a query to select several fields from the table including a multi-value field. I then use the "DoCmd.TransferSpreadsheet acExport acSpreadsheetTypeExcel12" to send the info to an excel.xlsm...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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...

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.