SQL:从sql列值中检索前三个字符

时间:2019-04-12 13:16:40

标签: sql sql-server

例如:如果sql列的值是sa,123k,并且输出应前三个字符,即sak

字母和任何特殊字符都需要消除,并且只能得到三个字符。我们该怎么做?

4 个答案:

答案 0 :(得分:5)

您可以为此使用递归CTE:

with t as (
      select 'sa,123k' as str
     ),
     cte as (
      select str, left(str, 1) as c, stuff(str, 1, 1, '') as rest, 1 as lev,
             convert(varchar(max), (case when left(str, 1) like '[a-zA-Z]' then left(str, 1) else '' end)) as chars
      from t
      union all
      select str, left(rest, 1) as c, stuff(rest, 1, 1, '') as rest, lev + 1,
             convert(varchar(max), (case when left(rest, 1) like '[a-zA-Z]' then chars + left(rest, 1) else chars end))
      from cte
      where rest > '' and len(chars) < 3
     )
select str, max(chars)
from cte
where len(chars) <= 3
group by str;

Here是db <>小提琴。

答案 1 :(得分:2)

这可能有帮助

DECLARE @VAR VARCHAR(100)= 'sa,1235JSKL', @RESULT VARCHAR(MAX)=''

SELECT @RESULT = @RESULT+ 
CASE WHEN  RESULT LIKE '[a-zA-Z]' THEN RESULT ELSE '' END 
FROM (
SELECT NUMBER, SUBSTRING(@VAR,NUMBER,1) AS RESULT
FROM MASTER..spt_values 
WHERE TYPE = 'P' AND NUMBER BETWEEN 1 AND LEN(@VAR)
)A
ORDER BY NUMBER

SELECT SUBSTRING(@RESULT,1,3)

如果要将其应用于“表”列,则需要使用相同的逻辑创建Scalar函数。您可以找到更多有关如何通过Googling创建标量函数的文章。

答案 2 :(得分:1)

您可以使用G Mastros编写的此功能。

Create Function [dbo].[RemoveNonAlphaCharacters](@Temp nvarchar(MAX))
Returns nvarchar(MAX)
AS
Begin

    Declare @KeepValues as nvarchar(MAX)
    Set @KeepValues = '%[^a-z]%'
    While PatIndex(@KeepValues, @Temp) > 0
        Set @Temp = Stuff(@Temp, PatIndex(@KeepValues, @Temp), 1, '')

    Return @Temp
End

然后简单地这样调用函数

SELECT LEFT(dbo.RemoveNonAlphaCharacters(colName), 3)
FROM TableName

参考:G Mastros answer on "How to strip all non-alphabetic characters from string in SQL Server" question.

答案 3 :(得分:-1)

嗯,这很丑陋,但是您可以替换所有您不喜欢的字符。

在您的示例中,这将是:

SELECT REPLACE (REPLACE (REPLACE (REPLACE ('sa,123k', '1', ''), '2', ''), '3', ''), ',', '')

很显然,如果需要替换所有数字和其他类型的字符,则需要大量替换。

根据您的评论进行编辑:

SELECT REPLACE (REPLACE (REPLACE (REPLACE (REPLACE (REPLACE (REPLACE (REPLACE (REPLACE (REPLACE (REPLACE (REPLACE ('123456gh,.!879k', '1', ''), '2', ''), '3', ''), ',', ''), '4', ''), '5', ''), '6', ''), '.', ''), '!', ''), '7', ''), '8', ''), '9', '')