0

Есть переменная с xml-документом.

DECLARE @docxml xml;
SET @docxml='<Root>
                <Order>
                <Items>
                    <Product ProductID="1" ProductName="Book1" ProductCategory="A">
                        <Price val="RUB" PValue="300"/>
                        <Autors lang="русский">
                            <Autor>
                            Автор1
                            </Autor>
                            <Autor>
                            Автор2
                            </Autor>
                        </Autors>
                        <Features>
                        <Description>Описание товара Book1</Description>
                        <Garant>3 года</Garant>
                        </Features>
                    </Product>
                    <Product ProductID="2" ProductName="Book2" ProductCategory="F">
                        <Price val="DOL" PValue="50"/>
                        <Autors lang="английский">
                            <Autor>
                            Autor1
                            </Autor>
                            <Autor>
                            Autor1
                            </Autor>
                        </Autors>
                        <Features>
                        <Description>Описание товара Book2</Description>
                        <Garant>1 год</Garant>
                        </Features>
                    </Product>
                    <Product ProductID="3" ProductName="Book3" ProductCategory="A">
                        <Price val="RUB" PValue="700"/>
                        <Autors lang="русский">
                            <Autor>
                            Автор3
                            </Autor>
                            <Autor>
                            Автор4
                            </Autor>
                        </Autors>
                        <Features>
                        <Description>Описание товара Book3</Description>
                        <Garant>2 года</Garant>
                        </Features>
                    </Product>
                </Items>
                </Order>
                <Order>
                <Items>
                    <Product ProductID="4" ProductName="Book4" ProductCategory="A">
                        <Price val="RUB" PValue="900"/>
                        <Autors lang="русский">
                            <Autor>
                            Автор5
                            </Autor>
                        </Autors>
                        <Features>
                        <Garant>3 года</Garant>
                        </Features>
                    </Product>
                </Items>
                </Order>
            </Root>';

Необходимо вывести все атрибуты и элементы ProductID, Price и Autor

Делаю так:

DECLARE @docxml xml;
SET @docxml='<Root>
                <Order>
                <Items>
                    <Product ProductID="1" ProductName="Book1" ProductCategory="A">
                        <Price val="RUB" PValue="300"/>
                        <Autors lang="русский">
                            <Autor>
                            Автор1
                            </Autor>
                            <Autor>
                            Автор2
                            </Autor>
                        </Autors>
                        <Features>
                        <Description>Описание товара Book1</Description>
                        <Garant>3 года</Garant>
                        </Features>
                    </Product>
                    <Product ProductID="2" ProductName="Book2" ProductCategory="F">
                        <Price val="DOL" PValue="50"/>
                        <Autors lang="английский">
                            <Autor>
                            Autor1
                            </Autor>
                            <Autor>
                            Autor1
                            </Autor>
                        </Autors>
                        <Features>
                        <Description>Описание товара Book2</Description>
                        <Garant>1 год</Garant>
                        </Features>
                    </Product>
                    <Product ProductID="3" ProductName="Book3" ProductCategory="A">
                        <Price val="RUB" PValue="700"/>
                        <Autors lang="русский">
                            <Autor>
                            Автор3
                            </Autor>
                            <Autor>
                            Автор4
                            </Autor>
                        </Autors>
                        <Features>
                        <Description>Описание товара Book3</Description>
                        <Garant>2 года</Garant>
                        </Features>
                    </Product>
                </Items>
                </Order>
                <Order>
                <Items>
                    <Product ProductID="4" ProductName="Book4" ProductCategory="A">
                        <Price val="RUB" PValue="900"/>
                        <Autors lang="русский">
                            <Autor>
                            Автор5
                            </Autor>
                        </Autors>
                        <Features>
                        <Garant>3 года</Garant>
                        </Features>
                    </Product>
                </Items>
                </Order>
            </Root>';

CREATE TABLE txml (fx xml);
INSERT INTO txml (fx) VALUES (@docxml);
SELECT  T.C.value('../../@ProductID', 'int') AS ProductID,
        T.C.value('../../Price/@PValue', 'int') AS Price,
        T.C.value('text()[1]','varchar(15)') AS Autors
        
FROM txml a CROSS APPLY
            a.fx.nodes('/Root[1]/Order/Items/Product/Autors/Autor') AS T(C);

Не выводит Price, остальное если без Price делать, то выводит

4
  • Вы можете привести sql-код, который можно скопировать и сразу выполнить? 9 ноя 2022 в 19:16
  • Через FROM OPENXML я реализовал вывод ProductID, Price и Autor. А вот выше код что-то Price не выводится
    – monah
    9 ноя 2022 в 19:34
  • добавил код выше
    – monah
    9 ноя 2022 в 19:35
  • Пожалуйста, добавьте к вопросу ожидаемый результат на основе примера данных. 9 ноя 2022 в 20:07

2 ответа 2

1

Достаточно использовать Price[1] и ваш запрос заработает.

Я бы строил путь от общего родительского элемента, которым является Product.

SELECT  
  T.C.value('@ProductID', 'int') AS ProductID,
  T.C.value('Price[1]/@PValue', 'int') AS Price,
  T.C.value('Autors[1]', 'nvarchar(max)') AS Autors
        
FROM txml a CROSS APPLY
  a.fx.nodes('/Root[1]/Order/Items/Product') AS T(C);

В узле Autors может быть несколько значений Autor. Нужно получить их все или только первый? И т. к. там русский текст, то используем nvarchar.

В вашем варианте возвращается семь строк, по общему количеству авторов. В моём - 4 строки, по количеству продуктов (авторы при этом объединены).


Как объединить атрибуты PValue и val?

Вариант с функцией concat T-SQL:

concat(T.C.value('Price[1]/@PValue', 'int'), ' ', T.C.value('Price[1]/@val', 'varchar(3)')) AS Price1,

Вариант с функцией concat xquery:

T.C.query('text{concat(Price[1]/@PValue, " ", Price[1]/@val)}').value('.', 'varchar(15)') as Price2,
2
  • Спасибо! И еще вопрос: можно при выводе как-то объединить в один столбец Price атрибуты PValue и val? Или все таки их надо по отдельности выводить?
    – monah
    9 ноя 2022 в 19:51
  • @monah - обновил ответ 9 ноя 2022 в 20:17
1

Пожалуйста, попробуйте следующее решение.

Примечательные моменты:

  • Валюта получила свой собственный столбец.
  • Столбец авторов показывает всех авторов.

SQL

DECLARE @tbl TABLE (fx xml);
INSERT INTO @tbl (fx) VALUES
(N'<Root>
    <Order>
        <Items>
            <Product ProductID="1" ProductName="Book1" ProductCategory="A">
                <Price val="RUB" PValue="300"/>
                <Autors lang="русский">
                    <Autor>Автор1</Autor>
                    <Autor>Автор2</Autor>
                </Autors>
                <Features>
                    <Description>Описание товара Book1</Description>
                    <Garant>3 года</Garant>
                </Features>
            </Product>
            <Product ProductID="2" ProductName="Book2" ProductCategory="F">
                <Price val="DOL" PValue="50"/>
                <Autors lang="английский">
                    <Autor>Autor1</Autor>
                    <Autor>Autor1</Autor>
                </Autors>
                <Features>
                    <Description>Описание товара Book2</Description>
                    <Garant>1 год</Garant>
                </Features>
            </Product>
            <Product ProductID="3" ProductName="Book3" ProductCategory="A">
                <Price val="RUB" PValue="700"/>
                <Autors lang="русский">
                    <Autor>Автор3</Autor>
                    <Autor>Автор4</Autor>
                </Autors>
                <Features>
                    <Description>Описание товара Book3</Description>
                    <Garant>2 года</Garant>
                </Features>
            </Product>
        </Items>
    </Order>
    <Order>
        <Items>
            <Product ProductID="4" ProductName="Book4" ProductCategory="A">
                <Price val="RUB" PValue="900"/>
                <Autors lang="русский">
                    <Autor>Автор5</Autor>
                </Autors>
                <Features>
                    <Garant>3 года</Garant>
                </Features>
            </Product>
        </Items>
    </Order>
</Root>');

SELECT c.value('@ProductID', 'INT') AS ProductID,
     c.value('(Price/@val)[1]', 'NVARCHAR(10)') AS Currency,
     c.value('(Price/@PValue)[1]', 'INT') AS Price,
     c.query('data(Autors/Autor)').value('. cast as xs:token?', 'NVARCHAR(MAX)') AS Authors
FROM @tbl
    CROSS APPLY fx.nodes('/Root/Order/Items/Product') AS t(c);

Результат

ProductID Currency Price Authors
1 RUB 300 Автор1 Автор2
2 DOL 50 Autor1 Autor1
3 RUB 700 Автор3 Автор4
4 RUB 900 Автор5

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.