简体   繁体   中英

Convert table to comma delimited string

I have a single row in a table variable that looks like this:

CanEdit | CanView | CanAdd | CanDelete

All columns are bit fields. I need to convert this table to a comma-delimited string like the following:

  • If the user has true for each column... E,V,A,D

  • If the user only has Edit and Add... E,A

How can I do this?

As it's a fixed set, it can be done directly as follows.

SUBSTRING(
    CASE WHEN CanEdit   = 1 THEN ',E' ELSE '' END
  + CASE WHEN CanView   = 1 THEN ',V' ELSE '' END
  + CASE WHEN CanAdd    = 1 THEN ',A' ELSE '' END
  + CASE WHEN CanDelete = 1 THEN ',D' ELSE '' END,
  2,
  7
)

That said, it is very rare that this is recommended.

If you are refactoring your data, this is reversing the atomicity of your data and is considered a fundamentally problematic anti-pattern in SQL.

If you are doing this for presentation in a client, doing this in SQL couples your data layer and presentation layer, another anti-pattern.

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