日期:2014-05-18  浏览次数:20366 次

怎么用T-SQL语句 取出 "\客厅\古典\pgkt-gd0375.jpg" 中以这种格式显示 客厅,古典
怎么用T-SQL语句 取出 "\客厅\古典\pgkt-gd0375.jpg" 中以这种格式显示 客厅,古典 

"\客厅\现代古典\pgkt-xg0194.jpg"中 显示 客厅,现代古典

谢谢阿

------解决方案--------------------
SQL code
create table ta( col varchar(100))
insert ta select
'\客厅\现代古典\pgkt-xg0194.jpg' union all select
'\客厅\古典\pgkt-gd0375.jpg'

go

--加一个分隔函数:
create  function F_split(
                @s varchar(8000),          --包含多个数据项的字符串
                @pos int,                 --要获取的数据项的位置
                @split varchar(10)        --数据分隔符
)RETURNS varchar(100)
AS
BEGIN
    IF @s IS NULL RETURN(NULL)
    DECLARE @splitlen int                --分隔符长度
    SELECT @splitlen=LEN(@split+'a')-2
    WHILE @pos>1 AND charindex(@split,@s+@split)>0
        SELECT @pos=@pos-1,
            @s=stuff(@s,1,charindex(@split,@s+@split)+@splitlen,'')
    RETURN(nullif(left(@s,charindex(@split,@s+@split)-1),''))
END
GO

select dbo.F_split(col,2,'\'),dbo.F_split(col,3,'\')
from ta

drop table ta
drop function F_split
/*
                                             
------------------------------------------------ ----------------
客厅                                      现代古典
客厅                                      古典

(所影响的行数为 2 行)

*/

------解决方案--------------------
SQL code
create table ta( col varchar(100))
insert ta select
'\客厅\现代古典\pgkt-xg0194.jpg' union all select
'\客厅\古典\pgkt-gd0375.jpg'

go

--加一个分隔函数:
create  function F_split(
                @s varchar(8000),          --包含多个数据项的字符串
                @pos int,                 --要获取的数据项的位置
                @split varchar(10)        --数据分隔符
)RETURNS varchar(100)
AS
BEGIN
    IF @s IS NULL RETURN(NULL)
    DECLARE @splitlen int                --分隔符长度
    SELECT @splitlen=LEN(@split+'a')-2
    WHILE @pos>1 AND charindex(@split,@s+@split)>0
        SELECT @pos=@pos-1,
            @s=stuff(@s,1,charindex(@split,@s+@split)+@splitlen,'')
    RETURN(nullif(left(@s,charindex(@split,@s+@split)-1),''))
END
GO

select dbo.F_split(col,2,'\'),dbo.F_split(col,3,'\')
from ta

drop table ta
drop function F_split
/*
                                             
------------------------------------------------ ----------------
客厅                                      现代古典
客厅                                      古典

(所影响的行数为 2 行)

*/

------解决方案--------------------
SQL code
create table tb(s varchar(100))
insert into tb select '\客厅\古典\pgkt-gd0375.jpg'
insert into tb select '\客厅\现代古典\pgkt-xg0194.jpg'

select 
parsename(replace(replace(s,'.',''),'\','.'),3)+','+
parsename(replace(replace(s,'.',''),'\','.'),2)
from tb

------解决方案--------------------
SQL code
declare @t table(str varchar(40))
insert into @t values('\客厅\古典\pgkt-gd0375.jpg')
insert into @t values('\客厅\现代古典\pgkt-xg0194.jpg')

select
    parsename(str,4)+','+parsename(str,3) as str
from
    (select replace(stuff(str,1,1,''),'\','.') as str from @T) a

/*
str
-------------------
客厅,古典
客厅,现代古典
*/