包含数字的SQL服务器字符串或VARCHAR操作

时间:2017-06-15 07:56:53

标签: sql-server varchar reformatting

在SQL server中,我有VARCHAR值。

我需要一个自动重新格式化数据的视图。

以下列形式存储的数据:

hawthorn104freddy@hawthorn.com
scotland2samantha@gmail.com3
birmingham76roger@outlook.co.uk1905student

需要重新格式化为以下内容:

hawthorn  104freddy@hawthorn.com0000       
scotland  002samantha@gmail.com 0003       
birmingham076roger@outlook.co.uk1905student

重新格式化

  • 字符串中的数字值用零填充到最长数字的长度
  • 所有其他字符都填充空格字符以排列数字。

有谁知道这是怎么做的?

注意:请记住,字符串可能包含单词和数字的任意组合。

2 个答案:

答案 0 :(得分:0)

You should split your values to 4 columns (to find maximum length in each column), then add leading/trailing zeros/spaces, then concat it.

Here is code to split values, hope you will have no problems with adding zeros and spaces:

declare  @v varchar(255) = 'hawthorg104freddy@hawthorn.com50'
select 
    FirstPart   = left(@v, patindex('%[a-z][0-9]%', @v)), 
    SecondPart  = substring(@v, patindex('%[0-9]%', @v), patindex('%[0-9][a-z]%', @v) - patindex('%[a-z][0-9]%', @v)), 
    ThirdPart   = substring(@v, patindex('%[0-9][a-z]%', @v) + 1, len(@v) - patindex('%[0-9][a-z]%', @v) - patindex('%[0-9][a-z]%', reverse(@v))), 
    Fourthpart  = right(@v, patindex('%[0-9][a-z]%', reverse(@v)))

Notes:

patindex('%[a-z][0-9]%', @v) - Last letter in hawthorn (nickname?)

patindex('%[0-9][a-z]%', @v) - Last digit in first number (104)

patindex('%[0-9][a-z]%', reverse(@v)) - Length of the last number

You can also use CLR and RegEx to split values to groups: https://github.com/zzzprojects/Eval-SQL.NET/wiki/SQL-Server-Regex-%7C-Use-regular-expression-to-search,-replace-and-split-text-in-SQL

答案 1 :(得分:0)

您可以使用PATINDEX

declare @str varchar(100)='hawthorn104freddy@hawthorn.com'

SELECT SUBSTRING(@str,0,PATINDEX('%[0-9]%',@str)),
       SUBSTRING(@str,PATINDEX('%[0-9]%',@str),LEN(@str)-LEN(SUBSTRING(@str,0,PATINDEX('%[0-9]%',@str))))