从XML字段中获取存储为Varchar(max)的多个值

时间:2017-12-12 20:31:44

标签: sql-server

我在SQL Server的varchar(max)列中有这个值:

<VersionSeries><SeriesTypeIdList><int>3</int><int>4</int><int>2</int><int>29</int><int>31</int><int>32</int><int>39</int></SeriesTypeIdList></VersionSeries

我想将int值输出到表中。

这是我的代码,但它只返回它找到的第一条记录。

Declare @Version varchar(100)
Select @Version = '2016A Demo'

DECLARE @DataTable TABLE
(
    Xml XML NOT NULL,
    Code NVARCHAR(50) NULL

)
INSERT 
INTO @DataTable(Xml)
SELECT
    CONVERT(XML,CONVERT(NVARCHAR(max), Series))
FROM Version
where VersionName = @Version

Create table #SeriesCodes
  (Code integer)

  Insert Into #SeriesCodes
    (Code)
SELECT
     T.c.value('int[1]', 'nvarchar(50)') as Code
FROM  @DataTable d
    OUTER APPLY d.Xml.nodes('/VersionSeries/SeriesTypeIdList') T(c);


    Select * from #SeriesCodes

2 个答案:

答案 0 :(得分:0)

像这样:

Declare @Version varchar(100)
Select @Version = '2016A Demo'

DECLARE @DataTable TABLE
(
    Xml XML NOT NULL,
    Code NVARCHAR(50) NULL

)
INSERT 
INTO @DataTable(Xml)
values (N'<VersionSeries><SeriesTypeIdList><int>3</int><int>4</int><int>2</int><int>29</int><int>31</int><int>32</int><int>39</int></SeriesTypeIdList></VersionSeries>')

SELECT
     T.c.value('.', 'nvarchar(50)') as Code
FROM  @DataTable d
    OUTER APPLY d.Xml.nodes('/VersionSeries/SeriesTypeIdList/int') T(c);

答案 1 :(得分:0)

这是一个单一的陈述,可以得到你想要的东西:

DECLARE @x2 XML = N'<VersionSeries><SeriesTypeIdList><int>3</int><int>4</int><int>2</int><int>29</int><int>31</int><int>32</int><int>39</int></SeriesTypeIdList></VersionSeries>';

SELECT t.c.query(N'.').value(N'(/*)[1]', N'int') AS [int_value]
FROM   @X2.nodes(N'/VersionSeries/SeriesTypeIdList/*') AS [t]([c]);