基于以下link: 我们可以将表转换为xml
表格
USE AdventureWorks2012;
GO
SELECT ProductModelID, Name
FROM Production.ProductModel
WHERE ProductModelID=122 or ProductModelID=119
FOR XML RAW, XMLSCHEMA
GO
XML:
<xsd:schema targetNamespace="urn:schemas-microsoft-com:sql:SqlRowSet1"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:sqltypes="http://schemas.microsoft.com/sqlserver/2004/sqltypes"
elementFormDefault="qualified">
<xsd:import namespace="http://schemas.microsoft.com/sqlserver /2004/sqltypes" schemaLocation="http://schemas.microsoft.com/sqlserver/2004/sqltypes/sqltypes.xsd" />
<xsd:element name="row">
<xsd:complexType>
<xsd:attribute name="ProductModelID" type="sqltypes:int" use="required" />
<xsd:attribute name="Name" use="required">
<xsd:simpleType sqltypes:sqlTypeAlias="[AdventureWorks].[dbo].[Name]">
<xsd:restriction base="sqltypes:nvarchar" sqltypes:localeId="1033" sqltypes:sqlCompareOptions="IgnoreCase IgnoreKanaType IgnoreWidth" sqltypes:sqlSortId="52">
<xsd:maxLength value="50" />
</xsd:restriction>
</xsd:simpleType>
</xsd:attribute>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<row xmlns="urn:schemas-microsoft-com:sql:SqlRowSet1" ProductModelID="122" Name="All-Purpose Bike Stand" />
<row xmlns="urn:schemas-microsoft-com:sql:SqlRowSet1" ProductModelID="119" Name="Bike Wash" />
基于以前的xml,我们如何创建sql表以便将数据插回到表:Production.ProductModel
?我需要一种适用于所有表而不是特定表的通用方法。
例如,我需要类似以下内容但更聪明(例如,从xmlschema中检索有关列名称及其类型的数据。)
DECLARE @xml XML
, @table NVARCHAR(50)
DECLARE @COLUMNS NVARCHAR(MAX)
, @COLUMNSBYTYPE NVARCHAR(MAX)
SET @xml = '<row><ProductModelID>1</ProductModelID><Name>Test</Name></row>
<row><ProductModelID>2</ProductModelID><Name>Test2</Name></row>'
SET @table = 'Production.ProductModel'
-- get columns name and their types
SET @COLUMNSBYTYPE = stuff(
(
select ',T.X.value(''('+C.Name+'/text())[1]'', ''' + 'nvarchar(max)' + ''') as '+C.Name
from @xml.nodes('row[1]/*') as T(X)
cross apply (
select T.X.value('local-name(.)', 'nvarchar(max)')
) as C(Name)
cross apply (
select DATA_TYPE from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME ='' + @table + '' and COLUMN_NAME = C.Name
) as CType
ORDER BY C.Name
for xml path(''), type
).value('text()[1]', 'nvarchar(max)')
, 1, 1, '')
-- transfrom xml to sql table
DECLARE @SQL nvarchar(max)
SET @SQL = 'select ' + @COLUMNSBYTYPE +
' from @x.nodes(''/row'') as T(X)'
exec sp_executesql @SQL, N'@x xml', @x = @xml
答案 0 :(得分:0)
您是否在寻找能够轻松完成此任务的应用?如果是,那么您可以尝试Total XML Converter,它可以批量转换xml到sql。