SQL Server字符串搜索和评估

时间:2016-11-03 12:10:52

标签: sql sql-server tsql

在SQL Server中,我想评估类似1.2.30.4.50的字符串,并使用0102300450输出。基本上在周期之前评估每个数字,如果它有一个数字并输出两位数,则用零填充它。如果数字已有两位数,则应保持不变。

2.5.99.10.1之类的字符串应评估为0205991001。请注意,9910之前没有零。

我知道以下查询将在第一个句点出现之前返回第一个数字。但我无法进一步采取这一点。任何帮助表示赞赏!

如果col包含一个字符串1.2.30.4.50

SELECT left(col, charindex('.', col) - 1) FROM table 

将返回以下内容:

 column1    
 ---------- 
 1 

5 个答案:

答案 0 :(得分:2)

您可以如下

CREATE FUNCTION PrepareString
(    
    @val varchar(max), 
    @delimiter varchar(10)
)
RETURNS VARCHAR(MAX)
AS
BEGIN   

    DECLARE @xml as xml 
    SET @xml = cast(('<X>'+replace(@val,@delimiter ,'</X><X>')+'</X>') as xml)

    RETURN 
        (
            SELECT
                (
                    SELECT 
                         CASE WHEN LEN(N.value('.', 'varchar(MAX)')) = 1 THEN '0' + N.value('.', 'varchar(MAX)') ELSE N.value('.', 'varchar(MAX)') END 
                    FROM @xml.nodes('X') as T(N)
                    FOR XML PATH ('')
                ) A
        )
END
GO

示例:

SELECT dbo.PrepareString('2.5.99.10.1', '.') -- 0205991001
SELECT dbo.PrepareString('1.2.30.4.50', '.') -- 0102300450
SELECT dbo.PrepareString('1.2.30.4.50.123.3.443.2', '.') -- 01023004501230344302

答案 1 :(得分:1)

我的第一个想法是使用ParseName(),但观察次数太多

Declare @String varchar(50) = '2.5.99.10.1'
Select right('0'+Pos1,2)+right('0'+Pos2,2)+right('0'+Pos3,2)+right('0'+Pos4,2)+right('0'+Pos5,2)
 From  [dbo].[udf-Str-Parse-Row](@String,'.')

返回

0205991001

行解析UDF

CREATE FUNCTION [dbo].[udf-Str-Parse-Row] (@String varchar(max),@Delimiter varchar(10))
Returns Table 
As
Return (
    Select Pos1 = xDim.value('/x[1]','varchar(max)')
          ,Pos2 = xDim.value('/x[2]','varchar(max)')
          ,Pos3 = xDim.value('/x[3]','varchar(max)')
          ,Pos4 = xDim.value('/x[4]','varchar(max)')
          ,Pos5 = xDim.value('/x[5]','varchar(max)')
          ,Pos6 = xDim.value('/x[6]','varchar(max)')
          ,Pos7 = xDim.value('/x[7]','varchar(max)')
          ,Pos8 = xDim.value('/x[8]','varchar(max)')
          ,Pos9 = xDim.value('/x[9]','varchar(max)')
     From (Select Cast('<x>' + Replace(@String,@Delimiter,'</x><x>')+'</x>' as XML) as xDim) A
)
--Select * from [dbo].[udf-Str-Parse-Row]('Dog,Cat,House,Car',',')
--Select * from [dbo].[udf-Str-Parse-Row]('John Cappelletti',' ')

答案 2 :(得分:1)

假设您不在SQL Server 2016上且无法使用string_split函数,则此类问题非常适合Jeff Moden's Tally Table based string split table valued function

创建功能:

CREATE FUNCTION [dbo].[DelimitedSplit8K]
--===== Define I/O parameters
        (@pString VARCHAR(8000), @pDelimiter CHAR(1))
--WARNING!!! DO NOT USE MAX DATA-TYPES HERE!  IT WILL KILL PERFORMANCE!
RETURNS TABLE WITH SCHEMABINDING AS
 RETURN
--===== "Inline" CTE Driven "Tally Table" produces values from 1 up to 10,000...
     -- enough to cover VARCHAR(8000)
  WITH E1(N) AS (
                 SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
                 SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
                 SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
                ),                          --10E+1 or 10 rows
       E2(N) AS (SELECT 1 FROM E1 a, E1 b), --10E+2 or 100 rows
       E4(N) AS (SELECT 1 FROM E2 a, E2 b), --10E+4 or 10,000 rows max
 cteTally(N) AS (--==== This provides the "base" CTE and limits the number of rows right up front
                     -- for both a performance gain and prevention of accidental "overruns"
                 SELECT TOP (ISNULL(DATALENGTH(@pString),0)) ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E4
                ),
cteStart(N1) AS (--==== This returns N+1 (starting position of each "element" just once for each delimiter)
                 SELECT 1 UNION ALL
                 SELECT t.N+1 FROM cteTally t WHERE SUBSTRING(@pString,t.N,1) = @pDelimiter
                ),
cteLen(N1,L1) AS(--==== Return start and length (for use in substring)
                 SELECT s.N1,
                        ISNULL(NULLIF(CHARINDEX(@pDelimiter,@pString,s.N1),0)-s.N1,8000)
                   FROM cteStart s
                )
--===== Do the actual split. The ISNULL/NULLIF combo handles the length for the final element when no delimiter is found.
 SELECT ItemNumber = ROW_NUMBER() OVER(ORDER BY l.N1),
        Item       = SUBSTRING(@pString, l.N1, l.L1)
   FROM cteLen l

GO

然后与for xml结合使用将行连接到列以获得结果。

-- Create some data.
declare @a table(String nvarchar(100));
insert into @a values
 ('1.2.30.4.50')
,('06.7.80.90.10')
,('01.20.3.40.5');

-- This is how the function returns the data.
select Item
        ,right('0' + cast(Item as varchar(10)),2) as PadItem
from dbo.DelimitedSplit8K('1.2.30.4.50','.');

-- This is how you use FOR XML to concatenate the rows back together.
select (select '' + right('0' + cast(Item as varchar(10)),2)
        from dbo.DelimitedSplit8K(a.String,'.')
        for xml path('')
        ) as Result
from @a a;

给你的结果如下:

Result
----------
0102300450
0607809010
0120034005

答案 3 :(得分:0)

请尝试以下方法:

DECLARE @Str VARCHAR(100) = '2.5.99.10.1' DECLARE @EvlStr VARCHAR(100) = '',@OutPut VARCHAR(100) = ''

WHILE LEN(@Str)&gt; 0 BEGIN

 IF CHARINDEX('.',@Str) = 0
 BEGIN
    SET @EvlStr = @Str
    SET @Str = ''
 END  
 ELSE
 BEGIN

    SELECT @EvlStr = SUBSTRING(@Str,0,CHARINDEX('.',@Str))                                          
    SELECT @Str = SUBSTRING(@Str,CHARINDEX('.',@Str)+1,LEN(@Str))
 END


 IF LEN(@EvlStr) = 1
       SET @OutPut = @OutPut + '0' + @EvlStr
 ELSE 
       SET @OutPut =  @OutPut + @EvlStr

END

SELECT @OutPut

答案 4 :(得分:0)

此解决方案基于以下内容:

  • 令牌数量:5
  • 最小令牌长度:1
  • 最大令牌长度:2
source 'https://rubygems.org'

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.0.0', '>= 5.0.0.1'
# Use Puma as the app server
gem 'puma', '~> 3.0'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.2'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby

# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.5'

gem 'mongoid', '~> 6.0'
gem 'bson_ext'
gem 'moped'
gem 'devise',  '~> 4.0'

group :development, :test do
  gem 'byebug', platform: :mri
  gem 'rspec-rails', '~> 3.0'
  gem 'factory_girl_rails', '~> 4.0'
  gem 'database_cleaner', '~> 1.0'
end

group :development do
  gem 'web-console'
  gem 'listen', '~> 3.0.5'
  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.0'
end

gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]