我有一个SQL查询,它将表的每个XML行导出到单个XML文件。该过程完美地运行,除了它停止并且不会立即处理所有行。我必须将行号更改为从中断处开始。它将使用此过程处理所有行而没有错误,但我希望它一次处理所有行。 这是我的问题:
DECLARE
@FILENAME VARCHAR(500),
@bcpcmd VARCHAR(2000),
@RN VARCHAR(10),
@i int;
DECLARE @Table table (RN int, IsDone char(1))
INSERT @Table SELECT RN, 0 FROM [x_rpt].[dbo].[x_abc] WHERE RN>=1 --this is where I update RN to process records where it leaves off--
SET @i=0
WHILE @i<= (SELECT COUNT(*) FROM @Table WHERE IsDone = '0')
BEGIN
SELECT TOP 1 @RN=RN FROM @Table WHERE IsDone = 0
SET @FILENAME = '"C:\temp\data\abc\Jan_2016_'+@RN+'.xml"'
SET @bcpcmd = 'BCP "SELECT [XML] from [x_rpt].[dbo].[x_abc] WHERE RN='+@RN+'" queryout "'
SET @bcpcmd = @bcpcmd + @FILENAME + '" -w -T -S "SERVER"'
EXEC master..xp_cmdshell @bcpcmd
UPDATE @Table set IsDone='1' where RN=convert(int,@RN)
SET @i=@i+1
END
答案 0 :(得分:0)
尝试使用基于CURSOR
的方法:
CREATE TABLE SomeDB.dbo.MockUp(RN INT,[XML] XML);
INSERT INTO SomeDB.dbo.MockUp VALUES
(1,N'<test RN="1"/>')
,(17,N'<test RN="17"/>')
,(-300,N'<test RN="-300"/>');
DECLARE
@FILENAME VARCHAR(500),
@bcpcmd VARCHAR(2000),
@rn INT;
DECLARE c CURSOR FOR SELECT RN FROM SomeDB.dbo.MockUp
OPEN c;
FETCH NEXT FROM c INTO @rn;
WHILE @@FETCH_STATUS = 0
BEGIN
SET @FILENAME = '"C:\SomePath\Jan_2016_'+CAST(@rn AS VARCHAR(MAX))+'.xml"'
SET @bcpcmd = 'BCP "SELECT [XML] from SomeDB.[dbo].MockUp WHERE RN='+CAST(@rn AS VARCHAR(MAX))+'" queryout "'
SET @bcpcmd = @bcpcmd + @FILENAME + '" -w -T -S ' + @@SERVERNAME
EXEC master..xp_cmdshell @bcpcmd
FETCH NEXT FROM c INTO @rn;
END
CLOSE c;
DEALLOCATE c;
GO
DROP TABLE SomeDB.dbo.MockUp
调整路径和数据库/架构/表/列名称......