0

I have a table tbl1

How can I split the column values by 10 (number of characters)

FROM:

Column1            
Butuan City Philippines
Zamboanga City Philippines
Manila City Philippines

TO:

Column1           Column2
Butuan Cit        y Philippines
Zamboanga         City Philippines
Manila Cit        y Philippines
1
  • 2
    You want y in column 2?? Commented Dec 15, 2015 at 5:36

4 Answers 4

4

You can use the SUBSTRING() function:

SELECT SUBSTRING(Column1, 1, 10) AS Column1,
    SUBSTRING(Column1, 11, LEN(Column1) - 10) AS Column2
FROM yourtable

Note that we do not have to worry about using indices in substring which are greater than the length of Column1, q.v. the documentation which states:

If start [second parameter] is greater than the number of characters in the value expression, a zero-length expression is returned.

and

If the sum of start and length is greater than the number of characters in expression, the whole value expression beginning at start is returned.

Sign up to request clarification or add additional context in comments.

2 Comments

If you give a static length, it won't give error if the column value length increases?? Like if column value is 'Llanfairpwllgwyngyll'
Your question doesn't make sense to me, but I believe my answer will work, without the need of resorting to LEFT() or any helper functions other than SUBSTRING().
0

Use LEFT and SUBSTRING string functions. Try this

DECLARE @str VARCHAR(100) = 'Zamboanga City Philippines'

SELECT LEFT (( @str ), 10),
       Substring (( @str ), 10 + 1, Len(@str)) 

Comments

0

You can use the LEFT, LEN, and SUBSTRING

SELECT LEFT(Column1,10) AS 'Column1'

SELECT SUBSTRING(Column1, LEN(LEFT(Column1,10)) + 1, LEN(Column1)) AS 'Column2'

Merge the two queries:

SELECT LEFT(Column1,10) AS 'Column1', 
       SUBSTRING(Column1, LEN(LEFT(Column1,10)) + 1, LEN(Column1)) AS 'Column2'

Comments

0

You can use the in-build SUBSTRING() function of SQL to achieve your expected result.

For E.g.

IF (LEN(Column1) > 10)
BEGIN
    SELECT SUBSTRING(Column1, 1, 10) AS Column1,SUBSTRING(Column1, 11, LEN(Column1) - 10) AS Column2
    FROM <TABLE>
END

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.