简体   繁体   English

将表转换为逗号分隔的字符串

[英]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 如果用户对每列都为真... E,V,A,D

  • If the user only has Edit and Add... E,A 如果用户只有编辑和添加... 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. 如果要重构数据,这会颠倒数据的原子性,并且在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. 如果您要在客户端进行演示,那么在SQL中执行此操作会将数据层和表示层耦合在一起,这是另一种反模式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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