sql-server-2005: How to perform a split on a pipe delimited string variable?

社会主义新天地 提交于 2020-01-15 20:22:19

问题


i have simple data coming in like this:

declare @string varchar(500) = "val1|val2|val3"

how could i split this out into a cte or something similar so i could user it in a later query:

select col1 from table where col2 = @valFromCTE

回答1:


This is a helpful and simple way to query a delimited string as if it were a table.

Taken from: http://www.mindsdoor.net/SQLTsql/ParseCSVString.html

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_ParseCSVString]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_ParseCSVString]
GO


create function fn_ParseCSVString
(
@CSVString  varchar(8000) ,
@Delimiter  varchar(10)
)
returns @tbl table (s varchar(1000))
as
/*
select * from dbo.fn_ParseCSVString ('qwe,c,rew,c,wer', ',c,')
*/
begin
declare @i int ,
    @j int
    select  @i = 1
    while @i <= len(@CSVString)
    begin
        select  @j = charindex(@Delimiter, @CSVString, @i)
        if @j = 0
        begin
            select  @j = len(@CSVString) + 1
        end
        insert  @tbl select substring(@CSVString, @i, @j - @i)
        select  @i = @j + len(@Delimiter)
    end
    return
end


GO


来源:https://stackoverflow.com/questions/7391473/sql-server-2005-how-to-perform-a-split-on-a-pipe-delimited-string-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!