连接nvarchar列并转换为XML

时间:2018-03-29 14:20:57

标签: sql-server xml

我当前正在获取一个整数行,然后将该行转换为哈希表中的Nvarchar,然后将其转换为XML。目标是在一个XML变量中返回所有值,如下所示:

<item id ="001"/><item id ="002"/><item id ="003"/><item id ="004"/><item id ="005"/>

目前我的代码将其返回为XML行,如下所示:

 col
---------------
<item id="60114" />
<item id="60116" />
<item id="60120" />
<item id="60122" />
<item id="60123" />
<item id="60124" />
<item id="60125" />
<item id="60129" />

这是我的代码,我已经通过了:

DROP TABLE #ClientNumber

DECLARE @XMLClientID NVARCHAR (MAX)

CREATE TABLE #ClientNumber (ID int identity(1,1), [XMLClientID] NVARCHAR(20))

INSERT INTO #ClientNumber 
SELECT '<item id ="'+ CAST([ClientId] AS NVARCHAR) + '"/>' AS [XMLClientID] FROM [dbo.].[MyView] WHERE Column = 'Condition' AND [ClientName] LIKE 'BLA%';


WITH xoutput AS (
  SELECT CONVERT(xml, [XMLClientID]) AS col
    FROM #ClientNumber)
SELECT *
 FROM xoutput

任何引导都会很棒,因为for XML不会起作用。

3 个答案:

答案 0 :(得分:1)

您可以使用整数值而不是转换并格式化它。

 CREATE TABLE tbl (id int);

 INSERT INTO tbl VALUES (60114), (60116), (60120), (60122)
 GO

 SELECT id
 FROM tbl item
 FOR XML AUTO

输出:

| XML_F52E2B61-18A1-11d1-B105-00805F49916B                                 |
| :----------------------------------------------------------------------- |
| <item id="60114"/><item id="60116"/><item id="60120"/><item id="60122"/> |

dbfiddle here

答案 1 :(得分:0)

试试这个:

declare @table table (col varchar(100))
insert into @table values
('<item id="60114" />'),
('<item id="60116" />'),
('<item id="60120" />'),
('<item id="60122" />'),
('<item id="60123" />'),
('<item id="60124" />'),
('<item id="60125" />'),
('<item id="60129" />')

select cast(col as xml) from @table for xml path('')

答案 2 :(得分:0)

感谢@John Cappelletti的链接。这是我的解决方案:

DECLARE @XMLClientID VARCHAR (MAX)
DECLARE @StringClientID VARCHAR (MAX)
DECLARE @XMLStringClient XML;


CREATE TABLE #ClientNumber (ID int identity(1,1), [XMLClientID] VARCHAR(20))

INSERT INTO #ClientNumber
--AMEND LINE BELOW TO SELECT TARGETS!!--
SELECT '<item id ="'+ CAST([ClientId] AS NVARCHAR) + '"/>' AS [XMLClientID] FROM [dbo.].[MyView] WHERE Column = 'Condition' AND [ClientName] LIKE 'BLA%';


SELECT DISTINCT [XMLClientID]  = STUFF((Select '' +[XMLClientID] 
                           FROM  #ClientNumber
                           FOR XML Path(''),TYPE).value('(./text())[1]','varchar(max)'),1,0,'') 
                                            INTO #TempString
                                            FROM #ClientNumber A
SET @StringClientID = (SELECT [XMLClientID] FROM #TempString)
SET @XMLStringClient = CAST(@StringClientID AS XML);

EXEC dbo.My_StoredProcedure @XMLStringClient