0

I have column name in the table:

select LASTNAME
  FROM dbo.Employees
 WHERE LASTNAME = 'Smith'

and output of the above query is

LASTNAME
Smith

I want output like

   LASTNAME
      S
      m
      i
      t
      h
Nick Krasnov
  • 26,886
  • 6
  • 61
  • 78
user1444281
  • 39
  • 2
  • 6

3 Answers3

2

With a little help of a numbers table.

SQL Server:

select substring(E.LASTNAME, N.N, 1) as LASTNAME
from Employees as E
  inner join Numbers as N
    on N.N between 1 and len(E.LASTNAME)
order by E.LASTNAME, N.N

Oracle:

select substr(E.LASTNAME, N.N, 1) as LASTNAME
from Employees E
  inner join Numbers N
    on N.N between 1 and length(E.LASTNAME)
order by E.LASTNAME, N.N;

SQL Fiddle

Community
  • 1
  • 1
Mikael Eriksson
  • 136,425
  • 22
  • 210
  • 281
1

In SQL Server, if you don't have a table of numbers, then you can use CTE to generate the list:

;with cte (id, start, numb) as
(
  select id, 1 start, len(lastname) numb
  from employees
  union all
  select id, start + 1, numb
  from cte
  where start < numb
)
select c.id, substring(e.lastname, c.start, 1)
from employees e
inner join cte c
  on c.start between 1 and len(e.lastname)
  and c.id = e.id
order by e.id, e.lastname;

See SQL Fiddle With Demo

Taryn
  • 242,637
  • 56
  • 362
  • 405
0
-----  function for splitting   
CREATE FUNCTION [dbo].[SPLIT_Test] (  
@string VARCHAR(8000) )  
 RETURNS @table TABLE (strval VARCHAR(8000))  
AS  
BEGIN  
IF  LEN(@string)>=1
BEGIN
DECLARE @fulllen int=LEN(@string),@lastlen int=0
WHILE @fulllen>@lastlen
BEGIN
INSERT INTO @table
SELECT SUBSTRING(@string,1,1)
SET @string= RIGHT(@String, LEN(@String) - 1)
SET @lastlen=@lastlen+1
END
 RETURN 
END
RETURN   
END

---- query 
GO
DECLARE @name table(name varchar(500),row int IDENTITY(1,1))
INSERT INTO @name
select LASTNAME
  FROM dbo.Employees
 WHERE LASTNAME = 'Smith'
 DECLARE @Finalname table(name varchar(50))
DECLARE @startrow int =(SELECT MAX(row) FROM @name)
,@endrow int =1
WHILE  @startrow>=@endrow
BEGIN
INSERT INTO @Finalname
Select strval from [dbo].[SPLIT_test] ((SELECT name FROM @name where row=@endrow))         WHERE strval<>''-- removing empty spaces
SET @endrow=@endrow+1
END
SELECT * FROM @Finalname
Kumar_2002
  • 584
  • 1
  • 5
  • 14