View Single Post
Join Date: Oct 2005
Posts: 521
Reputation: pty is on a distinguished road 
Solved Threads: 37
pty's Avatar
pty pty is offline Offline
Posting Pro

Re: insert multiple rows in database

 
0
  #2
Oct 31st, 2005
Originally Posted by sweetyp
How do i insert multiple rows in database.
for example: I have 3 list:
list1: a1,a2,a3,a4
list2: b1,b2,b3,b4
list3: c1,c2,c3,c4

I want to insert a1,b1,c1 in 1st row. a2,b2,c2 in 2nd row,...
How do I write one sql insert statement to do that?
i'd imagine making a stored procedure to deal with the inserts would be the easiest way.

you can modify this sp to scroll through the list and put the whole lot of your list into variables then just insert 'em.

hope this helps


  1. /*******************************************************************************
  2. Description Delimit a string and return specified segment
  3. Author: Peter Yates
  4. Example usage: exec delimiter 'te~st~in~g1~23', '~', 5
  5. Modifications:
  6. *******************************************************************************/
  7.  
  8. IF EXISTS (SELECT *
  9. FROM dbo.sysobjects
  10. WHERE id = object_id(N'[dbo].[delimiter]')
  11. AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
  12. DROP procedure [dbo].[delimiter]
  13. go
  14.  
  15. CREATE procedure delimiter(
  16. @str nvarchar (4000), --delimited string
  17. @del nvarchar (10), --delimiter
  18. @sect int --section of string wanted
  19. )
  20. AS
  21. begin
  22. declare @nextstr nvarchar(4000)
  23. declare @pos int
  24. declare @nextpos int
  25. CREATE TABLE #valuetable (id int identity, value varchar(500))
  26. SET @nextstr = ''
  27. SET @str = @str + @del
  28. SET @pos = charindex(@del,@str)
  29. SET @nextpos = 1
  30. while (@pos <> 0)
  31. begin
  32. SET @nextstr = substring(@str,1,@pos - 1)
  33. INSERT INTO #valuetable
  34. ([value])
  35. VALUES
  36. (@nextstr)
  37. SET @str = substring(@str,@pos +1,len(@str))
  38. SET @nextpos = @pos
  39. SET @pos = charindex(@del,@str)
  40. end
  41. SELECT value
  42. FROM #valuetable
  43. WHERE id = @sect
  44. RETURN
  45. end
Reply With Quote