Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Easy Question about Stored Proc

Status
Not open for further replies.

nerdalert1

Programmer
Nov 4, 2004
92
US
How can I set this into a declared variable so I can use this in an IN Statement

DELCARE @CustList AS varchar(50)

SET @CustList = '1','2','3','4'

SELECT * from tblCustomer where CustNumb IN (@CustList)
 
see passing a list of values to a stored procedure faq183-3979

[bandito] [blue]DBomrrsm[/blue] [bandito]
 
You could throw your list into a temp table.

CREATE TABLE #tmpTable (CustomerID INT PRIMARY KEY)
INSERT INTO #tmpTable VALUES (1)
INSERT INTO #tmpTable VALUES (2)
INSERT INTO #tmpTable VALUES (3)
INSERT INTO #tmpTable VALUES (4)

Select * from tblCustomer where CustNumb in (Select CustomerID from #tmpTable)

Drop #tmpTable --not required
 
I use a nifty little UDF for putting comma delimited lists into SQL statements:

Code:
CREATE FUNCTION listToTable(@list as varchar(8000), @delim as varchar(10))
RETURNS @listTable table(
	Position int,
	Value varchar(8000)
	)
AS
BEGIN
	declare @myPos int
	set @myPos = 1

	while charindex(@delim, @list) > 0
	begin
		insert into @listTable(Position, Value)
		values(@myPos, left(@list, charindex(@delim, @list) - 1))

		set @myPos = @myPos + 1
		if charindex(@delim, @list) = len(@list)
			insert into @listTable(Position, Value)
			values(@myPos, '')
		set @list = right(@list, len(@list) - charindex(@delim, @list))
	end

	if len(@list) > 0
		insert into @listTable(Position, Value)
		values(@myPos, @list)

	RETURN
END

This is how it would be used:
Code:
DECLARE @list varchar(50)

SET @list = '1,2,3,4'

SELECT * FROM tblCustomers WHERE CustNum in (select value from dbo.listToTable(@list,','))
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top