-1

I am stuck searching for a way to do the following. I have a simple table which looks

+-------------------+----------+----------+
| coord             | lat      | lng      |
+-------------------+----------+----------+
| 9.08273, 10.92773 |          |          |
+-------------------+----------+----------+

What I want is

+-------------------+----------+----------+
| coord             | lat      | lng      |
+-------------------+----------+----------+
| 9.08273, 10.92773 |  9.08273 | 10.92773  |
+-------------------+----------+----------+

I looked at STRING_SPLIT and also at How do I split a string so I can access item x? @SO, but there does not seem to exist something like

STRING_SPLIT(columnname, ', ')[1]
STRING_SPLIT(columnname, ', ')[2]

to use this later maybe in a way like

UPDATE tablename SET lat = STRING_SPLIT(columnname, ', ')[1], SET lng = STRING_SPLIT(columnname, ', ')[2];

All approaches end up in creating

SEKTOR 8
  • 23
  • 4

1 Answers1

1

STRING_SPLIT is a table-valued function so returns a record for each string it splits out. You don't want multiple records. You simply want to split a single string so use CHARINDEX to find the position of the comma, the LEFT and SUBSTRING to carve up the string based on that position. Here's and an example of a similar technique using a Common Table Expression (CTE), being as you're new n all:

DROP TABLE IF EXISTS dbo.yourTable
GO

CREATE TABLE dbo.yourTable ( 
    coord   VARCHAR(30), 
    lat     DECIMAL(10,5),
    lng     DECIMAL(10,5)
)
GO

INSERT INTO dbo.yourTable ( coord )
VALUES ( '9.08273, 10.92773' )
GO

;WITH cte AS (
SELECT *, CHARINDEX( ',', coord ) commaPos
FROM dbo.yourTable
)
UPDATE cte
SET lat = LEFT( coord, commaPos - 1 ), 
    lng = SUBSTRING( coord, commaPos + 1, 20 )

SELECT *
FROM dbo.yourTable

My results:

My results

See the way I've created a test table and some sample data, and made the script re-runnable, you could do that for future questions, and who people what you've tried and what errors you get. This approach will generally get you a better response and attract less downvotes. I have upvoted your question, but it looks like you're already behind.

Have a look through How to create a Minimal, Reproducible Example and How does accepting an answer work? too, particularly if you've found the post helpful.

wBob
  • 13,710
  • 3
  • 20
  • 37