Execute stored procedure for each line in a CSV

Refresh

February 2019

Views

1.3k time

1

I am trying to run a stored procedure using tsql multiple times in a query using each CSV line for the parameters.

How would I go about looping through this?

Cheers

2 answers

1

I would suggest to import the csv file to a table and then process it by set wise insted of looping.You can modify your sproc to handle set based data.

3

If this can be achieved with a set bases operation (as recommended by AnnandPhadke), that is the way to go. Much more efficient. If not you can use a cursor as follows:

Import the csv into a table ImportedCSV

DECLARE @sSQL AS VARCHAR(5000)
DECLARE @sItemsFromCSV

DECLARE sql_cursor CURSOR
    FOR SELECT ItemsFromCSV FROM ImportedCSV
OPEN sql_cursor

FETCH NEXT FROM sql_cursor 
INTO @ItemsFromCSV  -- Multiple variables for multiple CSV columns will be required

WHILE @@FETCH_STATUS = 0
BEGIN

@sSQL = 'EXEC USP_MyProc ' + @ItemsFromCSV  -- AND OTHER Parameters
EXECUTE sp_executesql @sSQL

FETCH NEXT FROM sql_cursor
END 
CLOSE sql_cursor;
DEALLOCATE sql_cursor;

This will allow the execution of custom SQL per line in the CSV, including calling a stored procedure with multiple parameters.