I have a process that needs to split a string of key-value pairs. To do so, I'm using a combination of a temp table that has computed columns to calculate the key and the value from each key-value pair, and a string_split function in the INSERT statement to separate the key-value pairs into rows. This is how the table looks like:
CREATE TABLE #KeyValuePairs (
[PK] uniqueidentifier NOT NULL,
[KeyValue] varchar(500) NOT NULL,
[Key] AS CONVERT(varchar(35), SUBSTRING([KeyValue],1,CHARINDEX('=',[KeyValue])-1)) PERSISTED NOT NULL,
[Value] AS SUBSTRING([KeyValue],CHARINDEX('=',[KeyValue]) + 1, LEN([KeyValue]) - CHARINDEX('=',[KeyValue])) PERSISTED NULL
);
The clustered index just helps me to find a specific combination of primary key and value key efficiently. The following is how I insert data into it:
INSERT #KeyValuePairs ([PK], [KeyValue])
SELECT T.[PK], kv.[value]
FROM BaseTable T
CROSS APPLY string_split([KeyValueStringColumn],'*') kv
WHERE [KeyValueStringColumn] != ''
AND kv.[value] != ''
Occasionally, this query fails with the following error:
Invalid length parameter passed to the LEFT or SUBSTRING function.
If I remove the computation from the table definition, leaving the fields NULL by the INSERT and instead run an UPDATE afterwards with the exact same formula, the UPDATE succeeds always.
=
inside?*
and the key and value by=
. That and because an UPDATE after the insert never fails leads me to the only explanation being that the computation is done for blank fields even though they do not get inserted to the table.