-1

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

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

有什么解决办法吗?

4

1 回答 1

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
于 2012-09-27T05:56:37.873 回答