Day1 sql of Stack Exchange

1.Download StackExchange's open data
https://archive.org/details/stackexchange

2.Importing and Process data from XML files into SQL Server tables
https://www.mssqltips.com/sqlservertip/2899/importing-and-processing-data-from-xml-files-into-sql-server-tables/

step1.Importing XML data from XML file using OPENROWSET
对于第一个脚本,第一个创建数据库的命令我选择了注释掉改为手动创建该数据库,因为使用该命令创建的权限方面貌似有点问题。这个阶段遇到的第二个问题是导入的xml文件过大,sql server默认的配置是导入的xml文件有2M限制,在工具-选项里可以设置一下,设置完毕记得重启sql server。虽然这个问题解决了,但在导入400M左右的xml文件时,sql server报“System.OutOfMemoryException”的异常,猜测可能跟xml文件有关,因为在跑普通的table时,4G左右的表也没有出现这个问题,暂时先不解决了。

step2.Process XML data using OPENXML function

First call the sp_xml_preparedocument stored procedure by specifying the XML data which will then output the handle of the XML data that it has prepared and stored in internal cache.Then we will use the handle returned by the sp_xml_preparedocument stored procedure in the OPENXML function to open the XML data and read it.
这个过程按照XML层级的不同以及自己数据提取需求的不同,要针对性的写属性,外部架构都是一样的,关键是属性提取那里,目录都是写到需要提取的最深层级,然后用'../'来返回上一级(父亲节点,对这里是以树的形式存储临时数据的)。"EXEC sp_xml_removedocument @hDoc"语句用来释放内存。

step3.把查询结果存到新表中,以下是代码示例

USE Badges
GO

DECLARE @XML AS XML, @hDoc AS INT, @SQL NVARCHAR (MAX)

SELECT @XML = XMLData FROM XMLwithOpenXMLBadges

EXEC sp_xml_preparedocument @hDoc OUTPUT, @XML

CREATE TABLE Badges
(
UserId varchar(50),
Name varchar(100),
Date datetime
);

INSERT INTO Badges
SELECT UserId,Name,Date
FROM OPENXML(@hDoc,'badges/row')
WITH
(
UserId varchar '@UserId',
Name varchar '@Name',
Date datetime '@Date'
)

EXEC sp_xml_removedocument @hDoc
GO

你可能感兴趣的:(Day1 sql of Stack Exchange)