We need to change the way we populate the two temporary tables so that we use a MERGE instead of INSERTED. Using a Merge we would be able to query both the inserted table and the table it comes from which would allow us to guarantee the ordinals line up correctly.
INSERT dbo.Segment_1
(
Name,
Element,
)
OUTPUT
INSERTED.Segment_No
INTO dbo.#Segment_Log_Into_Table
SELECT
@Name,
LEFT(ISNULL(S.Formatted_Value, ''), 500)
FROM dbo.#Segment_Log_Table AS SLT
OUTER APPLY dbo.XYZFUNCION(SLT.Element, 'C') AS S
ORDER BY
SLT.Ordinal;
Structure:
Table1 - Segment_1(Name Varchar(500),Element varchar(500),Segment bigint)
Table2 - #Segment_Log_Into_Table(ORDINAL INT IDENTITY, Segment_No bigint)
Table3- #Segment_Log_Table(ORDINAL INT IDENTITY, Segment_No bigint)
We store the data into two temporary tables where we join the tables together in another below query based on an Ordinal but in some situations ordinal are wrong (not every time).
It looks like the way we handle this situation of ordinal creation doesn't guarantee the order of the second table to be the same as the first and below query end up with wrong\weird combination of element.
INSERT dbo.Segment_2
(
Name,
Element_Ext
)
SELECT
@Name,
SUBSTRING(ISNULL(S.Formatted_Value, ''), 501, LEN(ISNULL(S.Formatted_Value, '')) - 500)
FROM dbo.#Segment_Log_Table AS SLT
JOIN dbo.#Segment_Log_Into_Table AS SLIT
ON SLIT.Ordinal = SLT.Ordinal
OUTER APPLY dbo.XYZFunction(SLT.Element, 'C') AS S
WHERE LEN(SLT.Element) > 500
ORDER BY
SLT.Ordinal;
Above query returns wrong combinations