首页 > 解决方案 > 从表中的字符串中获取最后一个单词

问题描述

我正在尝试从ProjectSQL-Server 2017 中的表中获取最后一句话。

我的代码如下:

select 
reverse(substring(reverse(ProjectDescription),1, charindex(' ', reverse(ProjectDescription)) -1)) as LastWord
from Project 

如果我要求将表格隔离为一行,则该代码有效,但我需要字段中所有行的最后一个字ProjectDescription

当我运行上述代码时,出现以下错误:

传递给 LEFT 或 SUBSTRING 函数的长度参数无效。

请有人可以帮助我解决我哪里出错了。

标签: sql-server

解决方案


迟到的答案,仅作为指导发布。

无需拆分字符串。您的错误仅仅是因为 charindex() 返回零。简单的解决方法是在 charindex() 中添加一个“故障安全”,方法是在字符串中添加一个空格,从而确保命中。

此外,请注意肖恩的建议。几年前我有一个类似的拆分功能,并且对性能提升感到惊讶。

例子

Declare @YourTable Table ([ID] varchar(50),[ProjectDescription] varchar(50))  Insert Into @YourTable Values 
 (1,'Some Project Item or Description') -- Multiword strubg
,(2,'OneWord    ')                      -- One word with trailing blanks
,(3,NULL)                               -- A NULL value
,(4,'')                                 -- An Empty String

Select * 
      ,LastWord = right(rtrim([ProjectDescription]),charindex(' ',reverse(rtrim([ProjectDescription]))+' ')-1)
 From  @YourTable 

退货

ID  ProjectDescription                  LastWord
1   Some Project Item or Description    Description
2   OneWord                             OneWord
3   NULL                                NULL
4       

推荐阅读