表TA中有一字段Fields是按$分割的字符串,Fields
内饰精品$外饰精品$改装/配件$功能用品$美容/养护$香水/净化$车主用品$汽车电器$安全/应急$影音导航$
现在要求按$分割该字段 循环输出如下表
Fields
内饰精品
外饰精品
改装/配件
功能用品
美容/养护
香水/净化
车主用品
汽车电器
安全/应急
影音导航
求解sql语句写法。

解决方案 »

  1.   

    select substring(Fields+'$',b.number,charindex('$',Fields+'$',b.number+1)-b.number) X
    from ta a,master..spt_values b
    where b.type='p' and b.number between 1 and 100 and substring('$'+Fields,b.number,1)='$'
      

  2.   

    --> 测试数据: [ta]
    if object_id('[ta]') is not null drop table [ta]
    create table [ta] (Fields varchar(9))
    insert into [ta]
    select '内饰精品' union all
    select '外饰精品' union all
    select '改装/配件' union all
    select '功能用品' union all
    select '美容/养护' union all
    select '香水/净化' union all
    select '车主用品' union all
    select '汽车电器' union all
    select '安全/应急' union all
    select '影音导航'
    goselect substring(Fields+'$',b.number,charindex('$',Fields+'$',b.number+1)-b.number) X
    from ta a,master..spt_values b
    where b.type='p' and b.number between 1 and 100 and substring('$'+Fields,b.number,1)='$'
      

  3.   

    --> 测试数据: [ta]
    if object_id('[ta]') is not null drop table [ta]
    create table [ta] (Fields varchar(100))
    insert into [ta]
    select '内饰精品$外饰精品$改装/配件$功能用品$美容/养护$香水/净化$车主用品$汽车电器$安全/应急$影音导航$'
    goselect substring(Fields,b.number,charindex('$',Fields,b.number+1)-b.number) X
    from ta a,master..spt_values b
    where b.type='p' and b.number between 1 and 100 and substring('$'+left(Fields,len(fields)-1),b.number,1)='$'
      

  4.   


    create table #test(
    id int identity(1,1),
    contents varchar(10)
    )
    go
    declare @str varchar(8000)
    set @str='内饰精品$外饰精品$改装/配件$功能用品$美容/养护$香水/净化$车主用品$汽车电器$安全/应急$影音导航$'
    select @str='insert #test(contents) select '+''''+replace(@str,'$',''''+' union all select '+'''')
    select @str=left(@str,len(@str)-19)
    print @str
    exec(@str)
    goselect * from #test/*
    id          contents
    ----------- ----------
    1           内饰精品
    2           外饰精品
    3           改装/配件
    4           功能用品
    5           美容/养护
    6           香水/净化
    7           车主用品
    8           汽车电器
    9           安全/应急
    10          影音导航(10 行受影响)
    */
      

  5.   

    ALTER FUNCTION [dbo].[split](@SourceSql VARCHAR(MAX),@StrSeprate VARCHAR(10))
    RETURNS @temp TABLE(Result VARCHAR(100)) 
    AS
    BEGIN
    DECLARE @i INT
    SET @SourceSql = RTRIM(LTRIM(@SourceSql))
    SET @i = CHARINDEX(@StrSeprate,@SourceSql)
    WHILE @i>=1 BEGIN
    INSERT @temp VALUES(LEFT(@SourceSql,@i-1))
    SET @SourceSql = SUBSTRING(@SourceSql, @i + 1, LEN(@SourceSql) - @i)
    SET @i = CHARINDEX(@StrSeprate,@SourceSql)
    END
    IF @SourceSql <> '\'
    INSERT @temp VALUES(@SourceSql)
    RETURN 
    END
    调用:SELECT * FROM split('ahod,ohfp,sado,apd,',',')