Import table data into stored proc

I have a table that contains some contact data I need to import into my database.

Basically I need to know how to loop through the table and send each record to a stored proc that adds users like below (I know my syntax is way off).  I don't know if I should use a while loop or what, but I need to have the table values for parameters in the stored proc.

SELECT FirstName, LastName, etc FROM dbo.Import
INTO usp_AddContact FirstName, LastName, etc
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

You can do something like this:


DECLARE @Counter INT, 
		  @FirstName VARCHAR(50), 
		  @LastName VARCHAR(50), 
SET @Counter = 1
SELECT ROW_NUMBER() OVER (ORDER BY FirstName, LastName, etc) AS Row, FirstName, LastName, etc 
INTO #Import
FROM dbo.Import
WHILE @Counter <= (SELECT MAX(Row) FROM #Import)
	SELECT @FirstName = FirstName, @LastName = LastName, etc
	FROM #Import
	WHERE Row = @Counter
	EXEC usp_AddContact @FirstName, @LastName, etc
	SET @Counter = @Counter + 1

Open in new window

You can also use a cursor as below:

	Declare @FirstName varchar(50);
	Declare @LastName varchar(50);
	DECLARE Contact_cursor CURSOR FOR
		select FirstName, LastName from <yourtableName>
	Open Contact_cursor
	FETCH NEXT FROM Contact_cursor into @FirstName, @LastName
			Exec usp_AddContact @FirstName, @LastName
			FETCH NEXT FROM Contact_cursor into @FirstName, @LastName
	CLOSE Contact_cursor
	DEALLOCATE Contact_cursor

Open in new window


Experts Exchange Solution brought to you by ConnectWise

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
sklarboddsAuthor Commented:
Thanks to both of you, I ended up using the cursor because it seemed the most straightforward.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.