Question

Passing in SQL Server Parameter in Where IN clause

Asked by: bugsnbre2

I have the following stored procedure:
---
create procedure uspGetRefills
@p varchar(255)
as
select * from uvwRefill
where Cast(MSRecID as varchar(255)) in (@p)
---
I want to pass in a list of parameters 'comma' delimited into the where clause.  Currently, I've tried the following:


----
uspGetRefills '1,2'
---

But it does't work.  However, if I do the following:
---
select * from uvwRefill
where Cast(MSRecID as varchar(255)) in ('1','2')
---
It returns what I need.  Now do I pass a parameter into SQL Server to get this to work?  Or will I need to build the SQL Statement Dynamically?

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2007-02-09 at 14:03:17ID22157124
Tags

sql

,

parameter

,

clause

,

server

Topics

SQL Server 2005

,

MS SQL Server

Participating Experts
8
Points
500
Comments
13

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. varchar comma-delimited for IN search...
    Have a stored proc that recieves a comma-delimited list of numbers as a varchar(150). In the WHERE clause of the sproc, I need to do the following but do not know the proper syntax... Please provide the correct code: WHERE table.type_id IN (@type_id) thank you!
  2. Tough SQL Query - Comma delimited fields
    First of all, I take no responsibility for the way the database was originally designed. Anyhow, here it is. MasterProducts ----------------------------------- sku | id | title | etc. Site #1 Products ----------------------------------- id | title | outputName | etc. Cat...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: SireesPosted on 2007-02-09 at 14:08:18ID: 18504926

Try modifying the procedure as

create procedure uspGetRefills
@p varchar(500)
as
begin
declare @SQL varchar(600)
set @SQL = 'select * from uvwRefill where Cast(MSRecID as varchar(255)) in ('+ @p+')'
EXEC(@SQL)
end      

 

by: BriCrowePosted on 2007-02-09 at 14:08:43ID: 18504930

you can't use a parameter this way without using dynamic sql with has its own drawbacks

DECLARE @sql varchar(1000)
SET @sql = 'SELECT * FROM uvwRefill WHERE MSRecID IN (' + @p + ')'
EXEC (@sql)

You don't need to cast it in this case.

 

by: ScottPletcherPosted on 2007-02-09 at 14:26:30ID: 18505030

By far the best solution is to parse @p into a table variable / temp table and then join on that.  This will produce a far better execution plan [SQL is optimized for doing joins] and the overheading of splitting a char string is relatively low.

DECLARE @recIds TABLE (
    recId INT,
    PRIMARY KEY (recId)  --will help performance!
    )

-- add code here to parse @p into the entries in the table below:
-- there are several examples on EE and on the web in general;
-- if you would like code added to do the split, just let me know.

-- ...code to parse / split goes here
-- ...

select *
from uvwRefill
inner join @recIds recIds ON recIds.recId = uvwRefill.MSRecID

 

by: angelIIIPosted on 2007-02-09 at 14:27:57ID: 18505039


you should avoid the dynamic sql olutions suggested above...

please create the following function:

CREATE FUNCTION dbo.ParmsToList (@Parameters varchar(500))
returns @result TABLE (Value varchar(30))
AS  
begin
     DECLARE @TempList table
          (
          Value varchar(30)
          )

     DECLARE @Value varchar(30), @Pos int

     SET @Parameters = LTRIM(RTRIM(@Parameters))+ ','
     SET @Pos = CHARINDEX(',', @Parameters, 1)

     IF REPLACE(@Parameters, ',', '') <> ''
     BEGIN
          WHILE @Pos > 0
          BEGIN
               SET @Value = LTRIM(RTRIM(LEFT(@Parameters, @Pos - 1)))
               IF @Value <> ''
               BEGIN
                    INSERT INTO @TempList (Value) VALUES (@Value) --Use Appropriate conversion
               END
               SET @Parameters = RIGHT(@Parameters, LEN(@Parameters) - @Pos)
               SET @Pos = CHARINDEX(',', @Parameters, 1)

          END
     END    
     INSERT @result
     SELECT value
        FROM @TempList
     RETURN
END    


and you will make your procedure like this:

create procedure uspGetRefills
@p varchar(255)
as
select * from uvwRefill
where MSRecID  in (select cast(value as int) from dbo.ParmsToList(@p)  )

 

by: ScottPletcherPosted on 2007-02-09 at 14:30:46ID: 18505053

How many rows are in uvwRefill?  If/as it becomes progressively bigger, your performance will get progressively worse.

 

by: bugsnbre2Posted on 2007-02-09 at 14:40:19ID: 18505106

There are 8200 rows in the view, but I will only be returning 5 or 6 at the most.

 

by: ScottPletcherPosted on 2007-02-09 at 14:55:54ID: 18505200

See you in a few months, when it grows and you post another q to figure out how to speed it up :-) (and we wonder why software development is moving offshore).

 

by: bugsnbre2Posted on 2007-02-09 at 15:14:22ID: 18505273

Not if I use your solution!!

 

by: BrandonGalderisiPosted on 2008-07-29 at 07:49:25ID: 22112006

This function will transform your delimited data into columns

drop function [dbo].[DelimitedToTable]
go
create function [dbo].[DelimitedToTable](@DelimitedString nvarchar(max), @Delimiter nvarchar(32))
returns @Values TABLE
     (ident         int not null identity primary key clustered
     ,theValue      nvarchar(1000)
     )
as
begin
declare    @e  int
          ,@i  int
set @i=1
set @e=1
 
set @DelimitedString=@DelimitedString+@Delimiter
 
while @e<>0 and @i<10
begin
     set @e=charindex(@Delimiter,@DelimitedString)
     if @e<>0
     begin
          insert into @Values (theValue)
          select substring(@DelimitedString,1,@e-1)
          set @DelimitedString = right(@DelimitedString, len(@DelimitedString)-@e)
     end
set @i=@i+1
end
return
end
GO
 
select theValue from [dbo].[DelimitedToTable]('a|basdf|c|d','|')
 
--Then to call it
 
 
select * from uvwRefill
where Cast(MSRecID as varchar(255)) in (select theValue from [dbo].[DelimitedToTable] (@p,','))
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:

Select allOpen in new window

 

by: groggyjavaPosted on 2009-06-19 at 14:13:22ID: 24670119

....or you could go for a much, much simpler approach

the money shot is the LIKE in the WHERE CLAUSE


CREATE PROCEDURE GET_ROWS
      @DelimitedList varchar(max),
        @Delimiter varchar(30),
AS
BEGIN
            SET @DelimitedList = @Delimiter + @DelimitedList + @Delimiter
            SELECT
                        FIELDX, et_al
            FROM
                        MyTable
            WHERE
                        (@DelimitedList LIKE '%' + @delimiter + FIELDX+ @delimeter + '%')
END

-- SEE WHAT I DID THERE?
-- I made the delimited list as the value to test with a LIKE clause,
-- and made the field the pattern to test
-- instead of the usual other way around

-- so if you have a row where FIELDX = 'XKCD'
-- this will be your test
-- '[XKCD|122317|107509|' LIKE '%|XKCD|%'

-- which is true.


-- then to call the code (probably would do this from app layer, but in sql for this discussion)

EXEC GET_ROWS
      @DelimitedList ='XKCD|122317|107509',
        @Delimiter = '|'



FOR THE RECORD, SPEEDWISE, IT PRETTY MUCH ROCKS

 

by: BrandonGalderisiPosted on 2009-06-19 at 17:55:57ID: 24671248

while your solution will scale similar in this case since they are doing a CAST of the searched column, mine will be faster when run against an indexed column since it will be doing equality searches and not double sided wildcard searches.

 

by: ValimaiPosted on 2010-07-14 at 16:48:26ID: 33209155

@groggyjava: lol, "money shot".

@BrandonGalderis: Thank you!!

Here is my version
I have modified the function so that I  always use delimiter ',' and have the returned value in the table as type int.
I have also renamed the function for my own convention. I have renamed the "theValue" field and I have change the input param to varchar(max)

IF OBJECT_ID(N'fn_delimitedtotable', N'TF') IS NOT NULL
	DROP FUNCTION fn_delimitedtotable;
GO

create function [dbo].[fn_delimitedtotable](@DelimitedString varchar(max))
returns @Values TABLE
(
	id int not null identity primary key clustered, 
	v int
)
as
begin
	declare @e int, @i int
	set @i = 1
	set @e = 1

	set @DelimitedString = @DelimitedString + ','
 
	while @e <> 0 and @i < 10
	begin
		 set @e = charindex(',', @DelimitedString)
		 if @e <> 0
		 begin
			  insert into @Values (v)
			  select substring(@DelimitedString, 1, @e - 1)
			  set @DelimitedString = right(@DelimitedString, len(@DelimitedString) - @e)
		 end
		set @i = @i + 1
	end
	return
end
GO

select v from [dbo].[fn_delimitedtotable]('1,2,3,4,5,6')

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:

Select allOpen in new window

 

by: tazz602Posted on 2011-01-24 at 15:26:27ID: 34687422

@BrandonGalderis: Thank you!!  Easy solution that I will use over and over again -

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...