I have a stored procedure that accepts a NVARCHAR(max) string that is JSON data that I need to validate before loading it into the live tables. If the validation fails I need to return a message with the issue and the row number of the bad data row. The rows do not have a number assigned in the JSON string but it is implied by the order that they are stored in the string. I am trying to assign a incremental number during the OPENJSON function.
When using XML I can do this:
SELECT ROW_NUMBER() OVER (ORDER BY item) AS rowOrder
, item.value('(./Id/text())[1]', 'bigInt') AS EId
, item.value('(./Name/text())[1]', 'nvarchar(255)') AS EName
, item.value('(./Number/text())[1]', 'nvarchar(30)') AS ENumber
FROM @ERow.nodes('/variable/item') AS main(item);
to derive it but that technique does not work with OPENJSON
I would rather not do it in two passes if possible - i.e. Load the data into a temp table and then update the rows in the temp table with a row number
SELECT ROW_NUMBER() OVER () AS rownum
, newColumnName
, decimal_column
, nvarchar_column
FROM OPENJSON(@JSON_String)
WITH (
newColumnName BIGINT '$.id_column',
decimal_column DEC(28,8),
nvarchar_column NVARCHAR(30)
)
Was thinking this would work but no luck.