2012-10-12 115 views
0

我有表中的列名:垂直輸出

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

與上述查詢的輸出是

LASTNAME 
Smith 

我要像

LASTNAME 
     S 
     m 
     i 
     t 
     h 

回答

2

輸出隨着一點點的幫助一個numbers table

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 Fiddle

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 @[email protected]+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>[email protected] 
BEGIN 
INSERT INTO @Finalname 
Select strval from [dbo].[SPLIT_test] ((SELECT name FROM @name where [email protected]))   WHERE strval<>''-- removing empty spaces 
SET @[email protected]+1 
END 
SELECT * FROM @Finalname 
1

在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; 

請參閱SQL Fiddle With Demo