如何使用tSQL删除字符串的最后一个字符?

时间:2012-07-11 18:59:52

标签: tsql

我需要的是在这种情况下删除逗号(,)的最后一个字符。

我尝试了Substring, Left, and Right个功能,但他们需要长度的字符串

以下是该方案: -

select 
(Case col1 & 1 When 1 Then 'Case 1,' Else '' End)  + 
(Case Col2 & 2 When 2 Then 'Case 2,' Else '' End)  +
(Case Col3 & 4 When 4 Then 'Case 4,' Else '' End)  
as Case
from table_01

2 个答案:

答案 0 :(得分:5)

好吧,就是不要删除最后一个逗号。请改为删除第一个

  • 使用STUFF()

    SELECT
      STUFF(
        (CASE col1 & 1 WHEN 1 THEN ',Case 1' ELSE '' END)
        + (CASE col1 & 2 WHEN 2 THEN ',Case 2' ELSE '' END)
        + (CASE col1 & 4 WHEN 4 THEN ',Case 4' ELSE '' END),
        1,
        1,
        ''
      ) AS [Case]
    FROM table_01
    
  • 使用SUBSTRING()

    SELECT
      SUBSTRING(
        (CASE col1 & 1 WHEN 1 THEN ',Case 1' ELSE '' END)
        + (CASE col1 & 2 WHEN 2 THEN ',Case 2' ELSE '' END)
        + (CASE col1 & 4 WHEN 4 THEN ',Case 4' ELSE '' END),
        2,
        999999  /* not necessary to calculate LEN()-1, any value
                   that is definitely greater than that will do */
      ) AS [Case]
    FROM table_01
    

答案 1 :(得分:3)

您可以使用以下内容,使用长度减1来为您提供所需的长度:

declare @string varchar(50)

set @string = 'testing, testing, testing,'

select substring(@string, 1, len(@string) -1)

结果:

testing, testing, testing

编辑:

您可以使用以下内容:

select substring(c, 1, len(c) -1)
from
(
  select 
    (Case When col1 = '1' Then 'Case 1,' Else '' End) +
    (Case When Col2 = '2' Then 'Case 2,' Else '' End) +
    (Case When Col3 = '4' Then 'Case 4,' Else '' End)  
    as C
  from t
) x

请参阅SQL Fiddle with Demo

相关问题