如何在每行中拆分/考虑3个字符

时间:2019-04-13 17:19:32

标签: sql-server-2008 sql-server-2012

嗨,我对sql server有疑问

如何在SQL Server中将3个字符的长度拆分为最后一个字符

table : emp 
id  | name  
1   | harikrishnaxx
2   | Baludevu

基于上述数据,我希望输出如下:

id  | name 
1   | har
1   |ikr
1   |ish
1   |nax
1   |x
2   | bal
2   |ude
2   |vu

我尝试如下: 首先,我创建表值函数,然后在emp表中调用此函数

create  FUNCTION DatesBetween(@name varchar(50))
RETURNS @dates TABLE (
   DateValue varchar(50)  NULL
) 
AS
BEGIN
declare @fin varchar(50)
declare @len int = (select len(@name))
declare @i int 
set @i=1
while (@i <=@len)
begin
insert into @dates (DateValue)values(@fin)
set  @fin =SUBSTRING (@name ,@i,3)
set @i=@i+3
   END;
 RETURN;
END;

select  id ,   dbo.DatesBetween(name ) from emp 

但以上查询未获得确切结果。 你能告诉我如何在sql server中解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

创建此内联表值用户定义函数,该函数可以适应您希望块大小的任何大小:

CREATE OR ALTER FUNCTION dbo.ChunkNames(@name varchar(50), @len int)
RETURNS TABLE
AS
  RETURN 
  (
    WITH n(n) AS 
    (
      SELECT n=1 UNION ALL 
      SELECT n+1 FROM n 
        WHERE n < LEN(@name)/@len
              + CASE LEN(@name)%@len WHEN 0 THEN 0 
                ELSE 1 END
    )
    SELECT n, chunk = SUBSTRING(@name,(n-1)*@len+1,@len) FROM n
  );
GO

现在,带有以下示例数据:

CREATE TABLE #emp
(id int, name sysname);

INSERT #emp(id,name) VALUES(1,'harikrishnaxx'),
  (2,'Baludevu'),(3,'woo'),(4,'booboo');

然后使用此查询:

SELECT e.id, name = f.chunk 
  FROM #emp AS e
  CROSS APPLY dbo.ChunkNames(e.name,3) AS f
  ORDER BY e.id, f.n;

您得到以下结果:

id  name
--  ----
1   har
1   ikr
1   ish
1   nax
1   x
2   Bal
2   ude
2   vu
3   woo
4   boo
4   boo

如果您需要重用此字符串以使其他字符串分开(可能超过100个字符),则必须在查询中添加OPTION (MAXRECURSION 0)