0

I have stored procedure & cursor loop which I am using to add data in main table issue is I am adding data from csv file to temp table and from temp table to main table

alter PROCEDURE [dbo].[CreateHub]
  @HubName varchar(100)
AS

INSERT INTO dbo.HUB1
                         (HUB_NAME)
SELECT        @HubName
WHERE        (NOT EXISTS
                             (SELECT        ID_HUB, HUB_NAME
                               FROM            dbo.HUB1
                               WHERE        (HUB1.hub_name = @HubName)))

SELECT        ID_HUB AS newHubId
FROM            dbo.HUB1
WHERE        (hub1.hub_name = @HubName)

GO

Once this is done, there is another code which is doing bulk insert from csv file and running cursor loop for adding data in main table

bulk insert [dbo].[HUB_temp]
from 'C:\POPAD-DAT\HUB1.csv'
with (fieldterminator = ',', rowterminator = '\n')
go

DECLARE @sSQL AS nVARCHAR(100)
DECLARE @ItemsFromCSV  AS nvarchar(200)

DECLARE sql_cursor_hub CURSOR
    FOR SELECT HUB_NAME FROM HUB_temp
OPEN sql_cursor_hub

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

WHILE @@FETCH_STATUS = 0
BEGIN

set @sSQL = 'EXEC  [dbo].[CreateHub] ' + @ItemsFromCSV  -- AND OTHER Parameters
print @sSQl
EXECUTE sp_executesql @sSQL

FETCH NEXT FROM sql_cursor_hub
END 

CLOSE sql_cursor_hub;

DEALLOCATE sql_cursor_hub;

Running cursor is not adding data its showing like same id and showing different u=hubname but not inserting data

While if I am running separately executing SP it is adding like this

EXEC  [dbo].[CreateHub] 'SGGSP30'
EXEC  [dbo].[CreateHub] 'USGSP20'

can you please help where exactly iam going wrong

1 Answer 1

1

You forgot to do INTO in the second fetch

WHILE @@FETCH_STATUS = 0
BEGIN

  set @sSQL = 'EXEC  [dbo].[CreateHub] ' + @ItemsFromCSV  -- AND OTHER Parameters
  print @sSQl
  EXECUTE sp_executesql @sSQL

  -- This is changed
  FETCH NEXT FROM sql_cursor_hub INTO @ItemsFromCSV
END 

You should also take care of your parameter declarations, @ItemsFromCSV is varchar(200) but the stored proc parameter is only varchar(100) and @sSQL is only 100 in size but you add @ItemsFromCSV to it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.