简体   繁体   English

在 T-SQL 中删除字符串中的最后一个字符?

[英]Remove the last character in a string in T-SQL?

How do I remove the last character in a string in T-SQL ?如何删除T-SQL中字符串的最后一个字符?

For example:例如:

'TEST STRING'

to return:回来:

'TEST STRIN'

eg例如

DECLARE @String VARCHAR(100)
SET @String = 'TEST STRING'

-- Chop off the end character
SET @String = 
     CASE @String WHEN null THEN null 
     ELSE (
         CASE LEN(@String) WHEN 0 THEN @String 
            ELSE LEFT(@String, LEN(@String) - 1) 
         END 
     ) END


SELECT @String

If for some reason your column logic is complex (case when ... then ... else ... end), then the above solutions causes you to have to repeat the same logic in the len() function.如果由于某种原因您的列逻辑很复杂(case when ... then ... else ... end),那么上述解决方案会导致您必须在 len() 函数中重复相同的逻辑。 Duplicating the same logic becomes a mess.复制相同的逻辑会变得一团糟。 If this is the case then this is a solution worth noting.如果是这种情况,那么这是一个值得注意的解决方案。 This example gets rid of the last unwanted comma.这个例子去掉了最后一个不需要的逗号。 I finally found a use for the REVERSE function.我终于找到了 REVERSE 函数的用途。

select reverse(stuff(reverse('a,b,c,d,'), 1, 1, ''))

试试这个:

select substring('test string', 1, (len('test string') - 1))

If your string is empty,如果您的字符串为空,

DECLARE @String VARCHAR(100)
SET @String = ''
SELECT LEFT(@String, LEN(@String) - 1)

then this code will cause error message 'Invalid length parameter passed to the substring function.'那么此代码将导致错误消息“传递给子字符串函数的长度参数无效”。

You can handle it this way:你可以这样处理:

SELECT LEFT(@String, NULLIF(LEN(@String)-1,-1))

It will always return result, and NULL in case of empty string.它将始终返回结果,并在空字符串的情况下返回 NULL。

即使源文本/var 为 null 或空,这也能工作:

SELECT REVERSE(SUBSTRING(REVERSE(@a), 2, 9999))
select left('TEST STRING', len('TEST STRING')-1)
@result = substring(@result, 1, (LEN(@result)-1))

如果您的 coloumn 是text而不是varchar ,那么您可以使用:

SELECT SUBSTRING(@String, 1, NULLIF(DATALENGTH(@String)-1,-1))

If you want to do this in two steps, rather than the three of REVERSE-STUFF-REVERSE, you can have your list separator be one or two spaces.如果您想分两步执行此操作,而不是三步 REVERSE-STUFF-REVERSE,您可以将列表分隔符设置为一或两个空格。 Then use RTRIM to trim the trailing spaces, and REPLACE to replace the double spaces with ','然后使用 RTRIM 修剪尾随空格,并使用 REPLACE 将双空格替换为 ','

select REPLACE(RTRIM('a  b  c  d  '),'  ', ', ')

However, this is not a good idea if your original string can contain internal spaces.但是,如果您的原始字符串可以包含内部空格,这不是一个好主意。

Not sure about performance.不确定性能。 Each REVERSE creates a new copy of the string, but STUFF is a third faster than REPLACE.每个 REVERSE 都会创建一个新的字符串副本,但 STUFF 比 REPLACE 快三分之一。

also see this也看到这个

I can suggest this -hack- ;).我可以建议这个 -hack- ;)。

select 
    left(txt, abs(len(txt + ',') - 2))
from 
    t;

SQL Server Fiddle Demo SQL Server 小提琴演示

This is quite late, but interestingly never mentioned yet.这已经很晚了,但有趣的是还没有提到。

select stuff(x,len(x),1,'')

ie: IE:

take a string x
go to its last character
remove one character
add nothing

you can create function你可以创建函数

CREATE FUNCTION [dbo].[TRUNCRIGHT] (@string NVARCHAR(max), @len int = 1)
RETURNS NVARCHAR(max)
AS
BEGIN
    IF LEN(@string)<@len
        RETURN ''
    RETURN LEFT(@string, LEN(@string) - @len)
END

获取最后一个字符

Right(@string, len(@String) - (len(@String) - 1))

Try this试试这个

DECLARE @String VARCHAR(100)
SET @String = 'TEST STRING'
SELECT LEFT(@String, LEN(@String) - 1) AS MyTrimmedColumn

I encountered this problem and this way my problem was solved:我遇到了这个问题,这样我的问题就解决了:

 Declare @name as varchar(30)='TEST STRING' Select left(@name, len(@name)-1) as AfterRemoveLastCharacter

My answer is similar to the accepted answer, but it also check for Null and Empty String.我的答案类似于已接受的答案,但它还会检查 Null 和 Empty String。

DECLARE @String VARCHAR(100)

SET @String = 'asdfsdf1'

-- If string is null return null, else if string is empty return as it is, else chop off the end character
SET @String = Case @String when null then null else (case LEN(@String) when 0 then @String else LEFT(@String, LEN(@String) - 1) end ) end

SELECT @String

I love @bill-hoenig 's answer;我喜欢@bill-hoenig 的回答; however, I was using a subquery and I got caught up because the REVERSE function needed two sets of parentheses.然而,我使用了一个子查询,因为 REVERSE 函数需要两组括号,所以我陷入了困境。 Took me a while to figure that one out!我花了一段时间才弄明白!

SELECT
   -- Return comma delimited list of all payment reasons for this Visit
   REVERSE(STUFF(REVERSE((
        SELECT DISTINCT
               CAST(CONVERT(varchar, r1.CodeID) + ' - ' + c.Name + ', ' AS VARCHAR(MAX))
          FROM VisitReason r1
          LEFT JOIN ReasonCode c        ON c.ID = r1.ReasonCodeID
         WHERE p.ID = r1.PaymentID
         FOR XML PATH('')
              )), 1, 2, ''))                        ReasonCode
  FROM Payments p

要通过修剪特定列的最后 N 个字符来更新记录:

UPDATE tablename SET columnName = LEFT(columnName , LEN(columnName )-N) where clause

Try It :尝试一下 :

  DECLARE @String NVARCHAR(100)
    SET @String = '12354851'
    SELECT LEFT(@String, NULLIF(LEN(@String)-1,-1))
declare @string varchar(20)= 'TEST STRING'
Select left(@string, len(@string)-1) as Tada

output:输出:

Tada
--------------------
TEST STRIN

Try this,试试这个,

DECLARE @name NVARCHAR(MAX) SET @name='xxxxTHAMIZHMANI****'SELECT Substring(@name, 5, (len(@name)-8)) as UserNames

And the output will be like, THAMIZHMANI输出将像 THAMIZHMANI

declare @x varchar(20),@y varchar(20)
select @x='sam'
select 
case when @x is null then @y
      when @y is null then @x
      else @x+','+@y
end


go

declare @x varchar(20),@y varchar(20)
select @x='sam'
--,@y='john'
DECLARE @listStr VARCHAR(MAX)   

SELECT @listStr = COALESCE(@x + ', ' ,'') +coalesce(@y+',','')
SELECT left(@listStr,len(@listStr)-1)

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

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