0

我有一个 Days 列,其中有一串 0 和 1 代表一周中的有效天数,为了清楚起见,我需要将其格式化或翻译成一串字母(取决于语言),例如“MTWtFSs”(英语)或“LMmJVSD” (西班牙语)。

此代码有效,但似乎太长了。还有其他想法吗?

DECLARE @i INT = 0
       ,@DaysBits VARCHAR(7) = '110010'
       ,@DaysLetters VARCHAR(7) = ''
       ,@DaysMask VARCHAR(7) = 'MTWtFSs'
WHILE @i < 7 
      BEGIN
            SET @i = @i + 1
            IF ( SUBSTRING(@DaysBits, @i, 1) = 1 ) 
               SET @DaysLetters = @DaysLetters + SUBSTRING(@DaysMask, @i, 1)
            ELSE 
               SET @DaysLetters = @DaysLetters + '_' 
      END
SELECT  @DaysBits AS 'Days Bits'
       ,@DaysLetters AS 'Days Letters'
4

1 回答 1

2

你用一个case

select case substring(@DaysBits, 1, 1) when 1 then substring(@DaysMask, 1, 1) else '_' end+
       case substring(@DaysBits, 2, 1) when 1 then substring(@DaysMask, 2, 1) else '_' end+
       case substring(@DaysBits, 3, 1) when 1 then substring(@DaysMask, 3, 1) else '_' end+
       case substring(@DaysBits, 4, 1) when 1 then substring(@DaysMask, 4, 1) else '_' end+
       case substring(@DaysBits, 5, 1) when 1 then substring(@DaysMask, 5, 1) else '_' end+
       case substring(@DaysBits, 6, 1) when 1 then substring(@DaysMask, 6, 1) else '_' end+
       case substring(@DaysBits, 7, 1) when 1 then substring(@DaysMask, 7, 1) else '_' end;

如果这对您来说有点太多代码,您可以使用数字表 1-7 并for xml path连接这些值。

select
  (
  select case substring(@DaysBits, N, 1) when 1 then substring(@DaysMask, N, 1) else '_' end
  from (values(1),(2),(3),(4),(5),(6),(7)) as T(N)
  order by N
  for xml path('')
  );

SQL小提琴

于 2013-02-25T08:37:28.877 回答