How to Split String by Character into Separate Columns in SQL Server
There are probably several different ways to do it, some uglier than others. Here's one:
(Note: dat = the string of characters)
select *,
substring(dat,1,charindex('-',dat)-1) as Section,
substring(dat,charindex('-',dat)+1,charindex('-',dat)-1) as TownShip,
reverse(substring(reverse(dat),0,charindex('-',reverse(dat)))) as myRange
from myTable
Please try more reliable code
CREATE BELOW FUNCTION
CREATE FUNCTION dbo.UFN_SEPARATES_COLUMNS(
@TEXT varchar(8000)
,@COLUMN tinyint
,@SEPARATOR char(1)
)RETURNS varchar(8000)
AS
BEGIN
DECLARE @POS_START int = 1
DECLARE @POS_END int = CHARINDEX(@SEPARATOR, @TEXT, @POS_START)
WHILE (@COLUMN >1 AND @POS_END> 0)
BEGIN
SET @POS_START = @POS_END + 1
SET @POS_END = CHARINDEX(@SEPARATOR, @TEXT, @POS_START)
SET @COLUMN = @COLUMN - 1
END
IF @COLUMN > 1 SET @POS_START = LEN(@TEXT) + 1
IF @POS_END = 0 SET @POS_END = LEN(@TEXT) + 1
RETURN SUBSTRING (@TEXT, @POS_START, @POS_END - @POS_START)
END
GO
AND Then try below code
DECLARE @STRING VARCHAR(20) ='1-668-333'
SELECT
dbo.UFN_SEPARATES_COLUMNS(@STRING, 1, '-') AS VALUE1,
dbo.UFN_SEPARATES_COLUMNS(@STRING, 2, '-') AS VALUE2,
dbo.UFN_SEPARATES_COLUMNS(@STRING, 3, '-') AS VALUE3
RESULT
If you need more understanding please go
https://social.technet.microsoft.com/wiki/contents/articles/26937.t-sql-splitting-a-string-into-multiple-columns.aspx