Hi @Charan P ,
Here is a solution that is based on combination of T-SQL and XQuery.
XQuery data model is based on sequences which is very handy for the scenario, i.e. sequences of tokens in this particular case.
The algorithm is as follows:
- Variable $n is a token that belongs to the ("test","tests") sequence.
- Variable $pos is a position of the preceding token.
- Variable $num is 1 or 0 based on the preceding token data type.
- The rest is a retrieval part that is splitting sequence of tokens into two columns based on the variables above.
SQL
-- DDL and sample data population, start
DECLARE @tbl TABLE (ID INT IDENTITY PRIMARY KEY, col VARCHAR(MAX));
INSERT INTO @tbl VALUES
('sql4 13434 22 test 39480'),
('sql2 DEF 39 tests'),
('data 123 258 256 tests 4587'),
('sql2 FED tests');
DECLARE @target TABLE (ID INT PRIMARY KEY, col VARCHAR(MAX), col1 VARCHAR(100), col2 VARCHAR(100));
-- DDL and sample data population, end
DECLARE @separator CHAR(1) = SPACE(1);
;WITH rs AS
(
SELECT *
, TRY_CAST('<root><r>' +
REPLACE(col, @separator, '</r><r>') +
'</r></root>' AS XML) AS xmldata
FROM @tbl
)
INSERT INTO @target (ID, col, col1, col2)
SELECT ID, col
, CAST(xmldata.query('let $n := /root/r[lower-case(.)=("test","tests")]
let $pos := count(/root/r[. << $n[1]])
let $num := if (number((/root/r[$pos]/text())[1]) instance of xs:double) then 1 else 0
return for $x in /root/r[position() le ($pos - $num)] return data($x)') AS VARCHAR(100)) AS col1
, CAST(xmldata.query('let $n := /root/r[lower-case(.)=("test","tests")]
let $pos := count(/root/r[. << $n[1]])
let $num := if (number((/root/r[$pos]/text())[1]) instance of xs:double) then 1 else 0
return for $x in /root/r[position() gt ($pos - $num)] return data($x)') AS VARCHAR(100)) AS col2
FROM rs;
-- test
SELECT * FROM @target;
Output
+----+-----------------------------+--------------+----------------+
| ID | col | col1 | col2 |
+----+-----------------------------+--------------+----------------+
| 1 | sql4 13434 22 test 39480 | sql4 13434 | 22 test 39480 |
| 2 | sql2 DEF 39 tests | sql2 DEF | 39 tests |
| 3 | data 123 258 256 tests 4587 | data 123 258 | 256 tests 4587 |
| 4 | sql2 FED tests | sql2 FED | tests |
+----+-----------------------------+--------------+----------------+