您好我试图从 XML 文件中获取一些信息到我的 MSSQL 数据库中,任何人都可以发现错误。
这是我的 sql 代码(现在修复了遍历整个目录和错误陷阱的循环)
使用 mydb
IF OBJECT_ID('mydb..tempList') IS NOT NULL
DROP TABLE tempList
CREATE TABLE tempList ([FileName] VARCHAR(500))
--plain vanilla dos dir command with /B switch (bare format)
INSERT INTO tempList
EXEC MASTER..XP_CMDSHELL 'dir C:\Data\icecat\xmls /B'
--delete the null values
DELETE tempList WHERE [FileName] IS NULL
-- Delete all the files that don't have xml extension
DELETE tempList WHERE [FileName] NOT LIKE '%.xml'
--this will be used to loop over the table
alter table tempList add id int identity
go
truncate table dbo.XMLImportRelated --in case you want to rerun just this codeblock
DECLARE @Directory varchar(100)
SELECT @Directory = 'C:\Data\icecat\xmls\'
DECLARE @FileExist int
DECLARE @FileName varchar(500),@DeleteCommand varchar(1000),@FullFileName varchar(500), @SQLFullFileName varchar(500)
DECLARE @ProductID int
DECLARE @RelatedID int
--这是为了让我们知道循环持续多长时间 DECLARE @LoopID int, @MaxID int SELECT @LoopID = min(id),@MaxID = max(ID) FROM tempList
WHILE @LoopID <= @MaxID
BEGIN
SELECT @FileNAme = filename
FROM tempList
WHERE id = @LoopID
SELECT @FullFileName = @Directory + @FileName
EXEC xp_fileexist @FullFileName , @FileExist output
IF @FileExist =1 --sanity check in case some evil person removed the file
BEGIN
DECLARE @x XML, @sql NVARCHAR(MAX);
BEGIN TRY
SELECT @sql = N'SELECT @X = CONVERT(xml,[ICECAT-interface],2)
FROM OPENROWSET(BULK ''' + @FullFileName + ''' ,SINGLE_BLOB)
---------------------^^ escaped quotes are important
AS Import([ICECAT-interface]);';
EXEC sp_executesql @sql, N'@x XML OUTPUT', @x OUTPUT;
END TRY
BEGIN CATCH
PRINT 'Error'
END CATCH
INSERT XMLImportRelated ([ProductID],RelatedID)
select P1.X.value('@ID', 'int') as ProductID,
P2.X.value('@ID', 'int') as RelatedID
from @X.nodes('/ICECAT-interface/Product') as P1(X)
cross apply P1.X.nodes('ProductRelated') as PR(X)
cross apply PR.X.nodes('Product') as P2(X)
-- SET @DeleteCommand = 'del ' + @Directory + @FileName
END
SELECT @LoopID = min(id)
FROM tempList
WHERE id > @LoopID
END
这是我试图使用的 xml 的 url
http://www.metatronics.co.uk/XML/3326091.xml
谢谢伙计们,我一直在得到空值,所以我错过了一些小东西,但是在整个早上看着它之后,我快疯了,约翰。