I am working on regular (monthly) import of a large amount of data. During the conversion, I split the row into several columns, but this is not just a simple split. There is some logic that decides which part of the line goes into which field.
I wrote a built-in function that breaks a string into several parts and gives you the value at the specified index.
Parameters:
- string value
- Delimiter
- Index
eg:
If the string value is X4-728Z5-121-84gff
and you want the function to give you 121, you call the function as follows:
fn_MyFunc('X4-728Z5-121-84gff', '-', 3)
My problem is this:
In my imported query, the index that I need for a specific field value depends on the value in another index. If the value in index 1 = X4
, then I want index 3, otherwise index 4.
In one request, I call this function 4 or 5 times, depending on the result of some case statements.
The function basically does the same thing over and over ... but each time I get a different index. How can I reduce the effort, so that the hard work of splitting the string is done only once, and in the same query, I can easily get different indexes?
Keep in mind that this happens when importing data from an external source, and any answer suggesting normalization or indexed views etc. will not help.
EDIT
I was asked to send my request:
SELECT ComplexString, CAST(fn_MyFunc(ComplexString, '-', 1) AS NVARCHAR(2)) AS LocationCode, CAST(fn_MyFunc(ComplexString, '-', 2) AS NVARCHAR(25)) AS CompanyCode, NULLIF(CASE WHEN fn_MyFunc(ComplexString, '-', 1) = 'R1' THEN NULL ELSE CAST(fn_MyFunc(ComplexString, '-', 3) AS INT) END, 0) AS ManagementType, CASE WHEN fn_MyFunc(ComplexString, '-', 1) = 'R1' THEN CAST(fn_MyFunc(ComplexString, '-', 3) AS VARCHAR(25)) ELSE CAST(fn_MyFunc(ComplexString, '-', 4) AS NVARCHAR(25)) END AS Network, . . . FROM MyTable