Sample Header Ad - 728x90

How to extract certificate attributes from a single column and split into many?

1 vote
2 answers
66 views
In my table I've a field (let say cert_attr) which stores [Certificate X.509 Attributes](https://docs.oracle.com/cd/E24191_01/common/tutorials/authz_cert_attributes.html) . Here is the example of 3 rows (each line corresponds to a field): "CN=User1, OU=Eng, O=Company Ltd, L=D4, S=Dublin, C=IE" "CN=User2, OU=Eng, O=Company Ltd, L=D2, S=Dublin, C=IE" "OU=Eng, O=Company Ltd" And I'm trying to split the value of a field into separate columns using SELECT in the following way: SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(cert_attr, "CN=", -1), ", ", 1) as CN, SUBSTRING_INDEX(SUBSTRING_INDEX(cert_attr, "OU=", -1), ", ", 1) as OU, SUBSTRING_INDEX(SUBSTRING_INDEX(cert_attr, "O=", -1), ", ", 1) as O, SUBSTRING_INDEX(SUBSTRING_INDEX(cert_attr, "L=", -1), ", ", 1) as L, SUBSTRING_INDEX(SUBSTRING_INDEX(cert_attr, "ST=", -1), ", ", 1) as ST, SUBSTRING_INDEX(SUBSTRING_INDEX(cert_attr, "C=", -1), ", ", 1) as C FROM mytable which works, however there is an issue for the rows which are missing some attributes. So in the case where the attribute is missing in the field's string, I expect the column to be empty, but it returns the whole string instead. The first two row examples are working as expected, which returns the following columns correctly: | CN | OU | O | L | S. | C | | ----- | --- | ----------- | -- | ------ | -- | | User1 | Eng | Company Ltd | D4 | Dublin | IE | | User2 | Eng | Company Ltd | D2 | Dublin | IE | The problem is with the 3rd row example, which I expect to return an empty string when the substring pattern is not found: | CN | OU | O | L | S. | C | | ---------- | --- | ----------- | ---------- | ---------- | ---------- | | OU=Eng,... | Eng | Company Ltd | OU=Eng,... | OU=Eng,... | OU=Eng,... | but instead the whole string is returned. **Question:** Is there any way to return an empty string when SUBSTRING_INDEX() fails to find the substring? Or maybe there is some other function (like a regular expression) or another workaround? My goal is to extract the data into TSV file by having these attributes in separate columns with valid values: mysql mytable cert_attributes.tsv
Asked by kenorb (475 rep)
Oct 23, 2020, 07:10 PM
Last activity: Mar 22, 2025, 03:28 PM