我在表中有列名:
select LASTNAME
FROM dbo.Employees
WHERE LASTNAME = 'Smith'
上述查询的输出是
LASTNAME
Smith
我想要像这样的输出
LASTNAME
S
m
i
t
h
我在表中有列名:
select LASTNAME
FROM dbo.Employees
WHERE LASTNAME = 'Smith'
上述查询的输出是
LASTNAME
Smith
我想要像这样的输出
LASTNAME
S
m
i
t
h
在数字表的帮助下。
SQL 服务器:
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
甲骨文:
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 Server 中,如果您没有数字表,则可以使用 CTE 生成列表:
;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;
----- 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