데이터엔지니어 군고구마
  • MsSQL Replace
    2015년 07월 01일 12시 07분 35초에 업로드 된 글입니다.
    작성자: DE 군고구마
    반응형

    작업을 하거나 어떠한 프로세스에 무엇을 추가 할때 문자를 자르거나 공백을 제거 하는 경우가 있다.

    특히 코드의 경우 DB상에서 잘라서 줘야 하거나 하는 경우가 있다. 이럴 때 공백을 제거하는 방법을 알아보자.

     

     

    1. 왼쪽 공백 제거 LTRIM

    DECLARE @string_to_trim varchar(60)

    SET @string_to_trim = '     Five spaces are at the beginning of this string.'

    SELECT 'Here is the string without the leading spaces: ' + LTRIM(@string_to_trim)

    SELECT 'Here is the string without the leading spaces: ' + @string_to_trim

    GO

     

    Here is the string without the leading spaces: 다음의 공백이 제거 된 것을 볼 수 있다.

    LTRIM으로 인하여 왼쪽 공백이 제거 되었다.

     

     

     

    2. 오른쪽 공백 제거 RTRIM

    DECLARE @string_to_trim varchar(60);

    SET @string_to_trim = 'Four spaces are after the period in this sentence.    ';

    SELECT @string_to_trim + ' Next string.';

    SELECT RTRIM(@string_to_trim) + ' Next string.';

    GO

     



    Four spaces are after the period in this sentence. 다음의 공백이 제거 된 것을 볼 수 있다.

    RTRIM으로 인하여 오른쪽 공백이 제거 되었다.

     

     

     

    3. 사이 공백제거 REPLACE

    REPLACE는 본래 문자를 찾아서 그 문자를 다른 문자로 대처하는 함수이다.

    하지만 공백을 제거하기 위해서 사용될 수 있다. 

    SELECT REPLACE('My Name is Joo',' ','')

     



    원리는 공백 즉 ' ' 을 찾아서 모든 공백을 ''으로 바꾸는 것이다.

     

     

     

     

    참조 : 

    http://msdn.microsoft.com/ko-kr/library/ms177827(SQL.105).aspx

    http://msdn.microsoft.com/ko-kr/library/ms178660(SQL.105).aspx

    반응형
    댓글