I am trying to update an integer value of a column based on partial data contained in a VARCHAR column

advertisements

Column A (VAR CHAR) contains a UNC Path eg.

lab03-app01\66\2016\10\3\LAB03-REC01\4989\1_6337230127359919046_6337230127366210371.wav

Within the UNC Path is an index number 4989.

I need to be able to update Column B (INT) to be equal to the value of Index Number located in Column A.

Is this possible?


This would be much easier with CLR and regular expressions.

One way of doing what you need in TSQL is below (demo).

DECLARE @T TABLE (A VARCHAR(255), B INT NULL);

INSERT INTO @T(A) VALUES ('lab03-app01\66\2016\10\3\LAB03-REC01\4989\1_6337230127359919046_6337230127366210371.wav')

UPDATE T
SET B = CAST(REVERSE(SUBSTRING(ReverseA, FinalSlash, PenultimateSlash - FinalSlash)) AS INT)
FROM @T T
CROSS APPLY (SELECT REVERSE(A))  ca1(ReverseA)
CROSS APPLY (SELECT 1 + CHARINDEX('\', ReverseA))  ca2(FinalSlash)
CROSS APPLY (SELECT CHARINDEX('\', ReverseA, FinalSlash))  ca3(PenultimateSlash);

SELECT *
FROM @T;