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?

campkev commented: very nice +1

Dani AI

Generated

Short summary and practical choices (pick one by input type and SQL Server version):

If your values are known at query time and there are only a handful, use the VALUES constructor — concise and set-based. If your input is three comma-delimited strings, parse each into rows that include an ordinal and join on that ordinal (set-based; avoid cursors). For newer servers prefer JSON/OPENJSON; for older servers use a splitter stored procedure or an XML approach.

Example — VALUES (SQL Server 2008+):

INSERT INTO MyTargetTable (col1, col2, col3)
VALUES ('v1','w1','x1'),
       ('v2','w2','x2'),
       ('v3','w3','x3');

Example — parse and pair three JSON arrays (SQL Server 2016+ with OPENJSON):

DECLARE @l1 NVARCHAR(MAX) = '["v1","v2","v3"]';
DECLARE @l2 NVARCHAR(MAX) = '["w1","w2","w3"]';
DECLARE @l3 NVARCHAR(MAX) = '["x1","x2","x3"]';

INSERT INTO MyTargetTable (col1, col2, col3)
SELECT j1.[value], j2.[value], j3.[value]
FROM OPENJSON(@l1) AS j1
JOIN OPENJSON(@l2) AS j2 ON j1.[key] = j2.[key]
JOIN OPENJSON(@l3) AS j3 ON j1.[key] = j3.[key];

Notes and troubleshooting

  • You cannot parameterize the column list directly (Texpert ran into this). Build a full INSERT statement and run it with sp_executesql; use QUOTENAME() for column names and pass values as parameters to avoid injection.
  • ’s stored-proc splitter is a good pre-2008 solution; ’s UNION approach is fine for a few static rows; ’s XML method works too — JSON/OPENJSON is usually simpler today.
  • Always validate that the three lists have the same number of elements before inserting; decide how to handle mismatches (ignore, pad, or error). For large volumes prefer set-based parsing (numbers/tally table or OPENJSON) for performance.

Recommended Answers

All 7 Replies

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

/*******************************************************************************
Description             Delimit a string and return specified segment
Author:                     Peter Yates
Example usage:        exec delimiter 'te~st~in~g1~23', '~', 5
Modifications:
*******************************************************************************/

if exists  (select * 
            from dbo.sysobjects 
            where id = object_id(N'[dbo].[delimiter]') 
            and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[delimiter]
go

create procedure delimiter(
 @str nvarchar (4000), --delimited string
 @del nvarchar (10), --delimiter
 @sect int --section of string wanted
 )
as
begin
 declare @nextstr nvarchar(4000)
 declare @pos int
 declare @nextpos int
 create table #valuetable (id int identity, value varchar(500))
 set @nextstr = ''
 set @str = @str + @del
 set @pos = charindex(@del,@str)
 set @nextpos = 1
 while (@pos <>  0)  
 begin
  set @nextstr = substring(@str,1,@pos - 1)
     insert into #valuetable 
      ([value]) 
      values 
      (@nextstr)
  set @str = substring(@str,@pos +1,len(@str))
  set @nextpos = @pos
  set @pos  = charindex(@del,@str)
 end
   select value 
   from #valuetable
   where id = @sect
 return
end

Why use a stored procedure when we can do it in one sql??

This is an example of how to to it ....

INSERT INTO SEND_RULE(MRT_CODE, ISSUING_COMPANY_CODE, CARD_BRAND_CODE, SEND_ISSUING_COMPANY_CODE)
(SELECT MRT_CODE, ISSUING_COMPANY_CODE, CARD_BRAND_CODE, ISSUING_COMPANY_CODE SEND_ISSUING_COMPANY_CODE
FROM CARD_MRT_CONTRACT)
ORDER BY MRT_CODE, ISSUING_COMPANY_CODE, CARD_BRAND_CODE;

:mrgreen:

Rohit Kumar Singh

P.S> Im the best ;-)

that would work if

a) the values were in another table

b) and they werent in a comma delimited list as per the original question :)

I tried to use your solution but while creating sp for inserting rows, I ran into a problem, My table has more columns so when I say
"Insert into table1 (col1,col2,col3) values (@Nextstr)"
the sp compiler gives me error that column list has more items than value list. So just to trick that I created a columnstr and passed @Columnstr into Insert statement so now it looks like
"Insert into table1 (@Columnstr) values (@Nextstr)"
now it compiles ok, but runtime it gives error 'table1 object not found'

any idea ? any help is deeply appreciated.

thanks in advance.
TJ

Just replying for anyone looking for an answer. Using MS SQL, you can do the following:

INSERT INTO test_table
SELECT 62
UNION
SELECT 91
UNION
SELECT 95
UNION 
SELECT 98
UNION 
SELECT 99

This will insert 5 rows into the table. Testing this on SQL Server 2000, the following works:

CREATE TABLE test
(
	val1 VARCHAR(10), 
	val2 VARCHAR(10), 
	val3 VARCHAR(10), 
	val4 VARCHAR(10)
)
GO

INSERT INTO test
(val1, val2, val3, val4)
(SELECT 'a1', 'a2', 'a3', 'a4')
UNION
(SELECT 'b1', 'b2', 'b3', 'b4')
UNION
(SELECT 'c1', 'c2', 'c3', 'c4')
GO

hey can you help me for making a frame on sql

It would be easier to use XML in SQL Server to insert multiple rows otherwise it becomes very tedious.

View full article with code explanations here [snipped]

Copy the following code into sql server to view a sample.

declare @test nvarchar(max)

set @test = '<topic><dialog id="1" answerId="41">
        <comment>comment 1</comment>
        </dialog>
    <dialog id="2" answerId="42" >
    <comment>comment 2</comment>
        </dialog>
    <dialog id="3" answerId="43" >
    <comment>comment 3</comment>
        </dialog>
    </topic>'

declare @testxml xml
set @testxml = cast(@test as xml)
declare @answerTemp Table(dialogid int, answerid int, comment varchar(1000))

insert @answerTemp
SELECT  ParamValues.ID.value('@id','int') ,
ParamValues.ID.value('@answerId','int') ,
ParamValues.ID.value('(comment)[1]','VARCHAR(1000)')
FROM @testxml.nodes('topic/dialog') as ParamValues(ID)

View full article with code explanations here [snipped]

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.