2011-09-12 5 views
1

내가 간단한 데이터는 다음과 같이오고있다 :sql-server-2005 : 파이프 구분 문자열 변수에서 분할을 수행하는 방법?

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

나는 CTE 또는 그래서 나중에 쿼리에 사용자를 할 수 비슷한으로 이것을 분할 수있는 방법 :

select col1 from table where col2 = @valFromCTE 
+0

는 분할 기능을 사용합니다. 당신은 내 대답을 여기에 예제를 볼 수 있습니다 : http://stackoverflow.com/questions/7274514/sql-query-to-match-keywords –

+0

내, 원시 입력 문자열 th3ough 때문에 012, 난 약간의 문제가 있습니다. – Cavide

+0

맞아요, 내가 수비수 인 테이블을보고 있습니다. – Cavide

답변

1

이것은이다 구분 된 문자열을 테이블 인 것처럼 쿼리하는 데 도움이되는 간단한 방법입니다.

은에서 촬영 : 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 
+1

작은 문자열에 대해서는 관련성이 없지만 큰 문자열에 대해서는 반복적 인 방법의 성능 관련성을 의식하고 있습니다. 나는 이것을 'INT'값으로 사용했지만, 작년에 여러 가지 분할 방법의 성능을 비교 했으므로 결과를 확인해야합니다. http://sqlblog.com/blogs/aaron_bertrand/archive/2010/07/07/splitting-a -list-of-integers-another-roundup.aspx –

관련 문제