日期:2014-05-18  浏览次数:20710 次

求sql拆分字符串的通用算法
我现在有一个字符串"1,2,3,4,(5,6),7,(8,(9,10))" 要统计,的个数
按常规 我想按 , 拆成7个 
1
2
3
4
(5,6)
7
(8,(9,10))
然后统计 , 的个数 本来这样 , 的个数应该是6个 就是说把(5,6),(8,(9,10))看成一体
不过我只会统计9个出来…… 
请问怎么解决 最好是标准sql,而其烦心的是这个括号还可能更多

------解决方案--------------------
探讨
SQL codedeclare @s varchar(100)
set @s='1,2,3,4,(5,6),7,(8,(9,10))'
select
(len(@s)-len(replace(@s,',','')))
+(len(@s)-len(replace(@s,'(','')))

------解决方案--------------------
看我的整理贴
http://topic.csdn.net/u/20090209/08/a945701c-e0d5-40cb-85f2-f4f56ac2999b.html
------解决方案--------------------
SQL code


--给我结个帖,一天没得几分....
alter function fun_charlen(@s varchar(8000)) 
returns int
as 
begin 
declare @startindex int,@endindex int
select @startindex=0,@endindex=0
while charindex('(',@s) >0 
begin 
set @startindex=charindex('(',@s) 
set @endindex=charindex(')',@s,@startindex+1)
while len(replace(substring(@s,@startindex,@endindex-@startindex+1),'(',''))<>len(replace(substring(@s,@startindex,@endindex-@startindex+1),')',''))
begin
    set @endindex=charindex(')',@s,@endindex+1)
end
if @endindex>0
set @s=stuff(@s,@startindex,@endindex-@startindex+1,'0')
end
return len(@s)-len(replace(@s,',',''))
end

------解决方案--------------------
更简单的作法



SQL code

DECLARE @s VARCHAR(1000)
SET @s='1,2,3,4,(5,6),7,(8,(9,10))'
SELECT TOP (LEN(@s)) ID=IDENTITY(INT),v=CAST(NULL AS CHAR) INTO #1 FROM sys.objects,sys.columns
UPDATE #1 SET v = SUBSTRING(@s,ID,1)
SELECT MIN(a.id) id1,b.id id2 INTO #2 FROM 
    (SELECT * FROM #1 WHERE v='(') a
CROSS APPLY
    (
        SELECT TOP 1 * FROM #1 x
            WHERE id>a.id 
                AND v=')'
                AND (SELECT SUM(CASE WHEN v='(' THEN 1 WHEN v=')' THEN -1 ELSE 0 END) FROM #1 WHERE ID<x.ID) = 1
    ) b
    GROUP BY b.id

ALTER TABLE #1 ADD gid INT NULL
GO

UPDATE a SET a.gid = ISNULL(id2,id)
    FROM #1 a
LEFT JOIN #2 b
    ON a.id BETWEEN id1 AND id2
SELECT COUNT(DISTINCT gid) FROM #1 WHERE v!=','
/*7*/
DROP TABLE #1,#2

------解决方案--------------------
修改一下
C# code
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.Text.RegularExpressions;

public partial class UserDefinedFunctions
{
    [Microsoft.SqlServer.Server.SqlFunction]
    public static SqlString Split()
    {
        // 在此处放置代码
        return new SqlString("Hello");
    }

    [Microsoft.SqlServer.Server.SqlFunction]
    public static SqlInt32 SplitTheComma(SqlString a)
    {
        Regex reg = new Regex(@"(?:\([^()]*(\([^()]*\)[^()]*)*\)),|[^()]*?,", RegexOptions.Compiled | RegexOptions.IgnoreCase);
        return (SqlInt32)reg.Matches(a.ToString()+",").Count-1;
    }
};