简体   繁体   中英

SQL: Find first occurrence of any character except the one specified

All,

Using SSMS v17.2

Long story short I have 15 columns in a table, each record in the table has a different number of columns filled out, the rest are null. I then concatenate the columns with a comma delimiter. Problem is the fields which are null also get concatenated leaving me with trailing commas.

ARNP,ACLS Provider,BLS Provider CPR,,,,,,,,,,,,
COC,CPC,CRC,CPC-1,,,,,,,,,,,
CISSP,CCNA Security,Network +,,,,,,,,,,,,
Leadership (All levels),Education (Grades K-12),,,,,,,,,,,,,,

As you can see the very last character before the trailing commas can be either alpha numeric or special characters. I need help removing these training commas up to the first character that is not a comma such as the below.

ARNP,ACLS Provider,BLS Provider CPR
COC,CPC,CRC,CPC-1
CISSP,CCNA Security,Network +
Leadership (All levels),Education (Grades K-12)

Thank you

This returns the correct data after concatenation:

SELECT LEFT(@MyData, charindex(',,', @Mydata) - 1)

This prevents the trailing commas from being concatenated:

SELECT Col1 + ',' + IsNull(Col2 + ',', '') + IsNull(Col3 + ',', '') + IsNull(Col4 + ',', '') + 
    IsNull(Col5 + ',', '') + IsNull(Col6 + ',', '') + IsNull(Col7 + ',', '') + IsNull(Col8 + ',', '') +
    IsNull(Col9 + ',', '') + IsNull(Col10 + ',', '') + IsNull(Col11 + ',', '') + 
    IsNull(Col12 + ',', '') + IsNull(Col13 + ',', '') + IsNull(Col14 + ',', '') + IsNull(Col15, '')

Actually, the above only works if concatenating a null returns a null. If this line:

SELECT 'xxx' + NULL

returns

xxx

then my second suggestion does not work

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM