-1

I am very new to SQL SCRIPT and I am trying to insert elements in a loop.I initially created a table "student" with two columns "id","name".

Now I have a CSV file of

1,"Sam"
2,"Ranger"
3,"Hardy"
4,"Micheal"

I want to insert these elements in a loop rather than using

insert into "student"(id,name) values(1,"Sam")

likewise for each entry.

I do not how to read the values from the CSV and insert it in a loop like

declare @id int 
select @id = 1
while @id >=1 and @id <= 4
begin
insert into student values(@id,@name)
select @id = @id + 1
end

Could anyone help me?Thanks in advance.

  • Which DBMS are you using? – a_horse_with_no_name Nov 3 '16 at 6:56
  • 1
    why do you want to insert using a loop instead of, for instance, bulk insert option ? – irimias Nov 3 '16 at 8:52
  • RBAR! you don't wanna do what you think you have to do – Nelz Nov 8 '16 at 13:24
1

Assuming Sql Server (and noticing that your data has double quotes), have a look at this post - Importing CSV with optional double quote text qualifier.

It discusses two options for importing data using a FORMAT file.

OPENROWSET and BULK INSERT

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.