游标不添加数据,仅在单独执行时添加

时间:2018-10-15 11:11:26

标签: sql-server tsql cursor dynamic-sql

我已使用存储过程和游标循环在主表中添加数据,这是我正在将csv文件中的数据添加到临时表中以及从临时表中添加数据到主表中

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

完成此操作后,还有另一个代码正在从csv文件进行批量插入并运行游标循环以在主表中添加数据

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;

运行光标未添加数据,其显示的ID相同,显示的u = hubname不同,但未插入数据

如果我运行单独执行的SP,则会添加这样的内容

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

您能帮我什么地方出问题吗

1 个答案:

答案 0 :(得分:1)

您忘记在第二次访存中执行INTO

updatedb
locate *.o

您还应该注意参数声明,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 是varchar(200),但是存储的proc参数仅为varchar(100),而@ItemsFromCSV的大小仅为100,但是您添加了{{ 1}}。