日期:2014-05-18 浏览次数:20724 次
--给我结个帖,一天没得几分.... 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
------解决方案--------------------
更简单的作法
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
------解决方案--------------------
修改一下
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; } };