In my table I've a field (let say cert_attr
) which stores Certificate X.509 Attributes.
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 < query.sql > cert_attributes.tsv
Best Answer
The first part is only to show you that the procedure works
db<>fiddle here
The complete stored procedure including producing the tsv file
Result tsv file
You must check the INTO OUTFILE folder, that must correspond with the entry in the my.ini/cnf file