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 TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Array / Insert statement 2

Status
Not open for further replies.

christer99

IS-IT--Management
Dec 3, 2001
247
Can I declare an array in MS SQL and then use an insert statement to loop through the array?
 
Start here faq183-5207

Let me know if this doesn't work for you

-George

Strong and bitter words indicate a weak cause. - Fortune cookie wisdom
 
We use the above technique ... a LOT. Works great.
======================
As examples, here's a function we built to convert a Comma Separated Value list of integers into a table. We use this silly little function in about 30 stored procs.
======================
ALTER FUNCTION CSVintTOTableOfIDs (@CSVs varchar(8000))
RETURNS @t TABLE(IDs int) AS
BEGIN
DECLARE @pos int, @comma varchar(1)
SET @comma=','
SET @pos=CHARINDEX(@comma,@CSVs)
WHILE @pos>0
BEGIN
INSERT @t values (cast((LEFT(@CSVs, CHARINDEX(@comma, @CSVs) - 1 )) as int))
SET @CSVs = SUBSTRING(@CSVs, CHARINDEX(@comma,@CSVs) + 1, LEN(@CSVs))
SET @pos = CHARINDEX(@comma,@CSVs)
END
IF LEN(@CSVs)>0
BEGIN
INSERT @t(IDs) SELECT @CSVs
END
RETURN
END
======================
And here's an example of how we use it.
======================
CREATE proc SpotsGridForOneClient(@ClientID int, @SpotIdsCSV varchar(300)) as
SELECT
FullName as Facility
FROM
Spots
WHERE
(Spots.ClientID = @ClientID) AND
(SpotTypes.SpotTypeID IN
(SELECT IDs from CSVintTOTableOfIDs(@SpotIdsCSV))
)
======================
Good luck

 
Yep!

Very similar to the SPLIT function shown in the faq's. The primary difference being... the version from the faq's allows you change the token that you split on. Wanna use commas, sure both do that, but if you want to use dashes (-), semi-colons (;), spaces, whatever, the version in the faq's allows it.

-George

Strong and bitter words indicate a weak cause. - Fortune cookie wisdom
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top