如何检查字符串是否包含某些字符并在SQL Server 2008 R2中将其拆分?

时间:2012-09-27 05:21:59

标签: sql-server-2008 tsql sql-server-2008-r2

我需要检查给定字符串中是否存在以下字符:

characters =('N', 'E', 'M', 'H', 'T', 'V', 'L', 'C' )
string = 2449.555N06704.2855EM0701H071T44.098V11.764L0.372C1

如果字符串包含这些字符,则需要将它们拆分为以下值,以便将它们插入details_Tb

N = 2449.7183 
E = 06704.2855 
T = 0701
H = 071
T = 44.098
V = 11.764
L = 0.372
C =  1

对此有任何解决方案吗?

1 个答案:

答案 0 :(得分:3)

如果您正在寻找此结果

<强>结果

N=2449.555
E=06704.2855
H=0701
T=071
V=44.098
L=11.764
C=0.372

然后尝试此查询..

DECLARE @CHARACTERS TABLE (CHARS CHAR(1)) 
INSERT INTO @CHARACTERS VALUES
('N'), ('E'), ('M'), ('H'), ('T'), ('V'), ('L'), ('C' );
DECLARE @STRING VARCHAR(500);
SET @STRING= '2449.555N06704.2855EM0701H071T44.098V11.764L0.372C1';

WITH CTE AS (
SELECT      CHARS+'='+CAST(REVERSE(LEFT(REVERSE(LEFT(@STRING,
            CHARINDEX(CHARS,@STRING,1)-1)), PATINDEX('%[^0-9,.]%',
            REVERSE(LEFT(@STRING,CHARINDEX(CHARS,@STRING,1)-1)) + 'Z')-1))
            AS VARCHAR(50)) AS RESULT
FROM        @CHARACTERS )
SELECT * FROM CTE WHERE LEN(RESULT)>2


EDIT1:根据评论,如果您要将这些值插入detail_Tb表,请检查以下代码:

create table detail_Tb(N float,E float,M float,
            H float,T float,V float,L float,C float);

DECLARE @CHARACTERS TABLE (CHARS CHAR(1)) 
INSERT INTO @CHARACTERS VALUES
('N'), ('E'), ('M'), ('H'), ('T'), ('V'), ('L'), ('C' );
DECLARE @STRING VARCHAR(500);
SET @STRING= '2449.555N06704.2855EM0701H071T44.098V11.764L0.372C1';
DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

;WITH CTE AS (
SELECT      CHARS,CAST(REVERSE(LEFT(REVERSE(LEFT(@STRING,
            CHARINDEX(CHARS,@STRING,1)-1)), PATINDEX('%[^0-9,.]%',
            REVERSE(LEFT(@STRING,CHARINDEX(CHARS,@STRING,1)-1)) + 'Z')-1))
            AS VARCHAR(50)) AS RESULT
FROM        @CHARACTERS )
SELECT * into #tmp FROM CTE WHERE len(RESULT)>2  


select @cols = STUFF((SELECT distinct ',' + QUOTENAME(CHARS) 
                    from #tmp
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'Insert into detail_Tb('+@cols+') 
              SELECT ' + @cols + ' from #tmp x
            pivot 
            (
                MAX([RESULT])
                for CHARS in (' + @cols + ')
            ) p '
execute(@query)     
Drop table #tmp