SQL2005下利用XML进行项目的合并与拆分
2010-04-20 00:00:00 来源:WEB开发网取特定分隔符分隔的串中指定位置的串
------------------------------------------------------------------------
-- Author: HappyFlyStone
-- Date : 2009-01-04 20:57:59
-- Ver: Microsoft SQL Server 2005 - 9.00.2047.00 (Intel X86)
-- Apr 14 2006 01:12:25
-- Copyright (c) 1988-2005 Microsoft Corporation
-- Standard Edition on Windows NT 5.0 (Build 2195: Service Pack 4)
--
------------------------------------------------------------------------
DECLARE @t TABLE(c VARCHAR(20))
INSERT @t SELECT '双桥,9.6米,30.0吨'
UNION ALL SELECT 'aa,bb,cc,dd'
--通常情况如果项目在四个项目以内时,推荐一种方法:
SELECT REPLACE(PARSENAME(XX,3),'$$','.') C ,
REPLACE(PARSENAME(XX,2),'$$','.') B
FROM
(
SELECT REPLACE(REPLACE(c,'.','$$'),',','.') XX FROM @T
)AA
--result
/*
c b
--------------------------------- -----------
双桥 9.6米
(所影响的行数为1 行)
*/
好,那我们来看看下XML如何处理的
SELECT A,B FROM
(SELECT CAST('<r>' + REPLACE(c,',','</r><r>') + '</r>' AS XML) x,c FROM @t) a
CROSS APPLY
(SELECT A=a.x.value('/r[1]','VARCHAR(10)'),B=a.x.value('/r[2]','VARCHAR(10)')) b
/*
A B
---------- ----------
双桥 9.6米
aa bb
(2 行受影响)
*/
更多精彩
赞助商链接