sql-server - 从表中的字符串中获取最后一个单词
问题描述
我正在尝试从Project
SQL-Server 2017 中的表中获取最后一句话。
我的代码如下:
select
reverse(substring(reverse(ProjectDescription),1, charindex(' ', reverse(ProjectDescription)) -1)) as LastWord
from Project
如果我要求将表格隔离为一行,则该代码有效,但我需要字段中所有行的最后一个字ProjectDescription
。
当我运行上述代码时,出现以下错误:
传递给 LEFT 或 SUBSTRING 函数的长度参数无效。
请有人可以帮助我解决我哪里出错了。
解决方案
迟到的答案,仅作为指导发布。
无需拆分字符串。您的错误仅仅是因为 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
推荐阅读
- python-3.x - Cannot install pycosat on alpine during dockerizing
- c# - 自定义 ILogger 实现设置
- bash - 使用 Azure CLI 从 bash 在 Azure VM 上运行命令
- html - Bootstrap 4.1 导航栏最大宽度和自动边距
- sql - SQlite 从表中为每个项目选择前 N 行
- jenkins-pipeline - Is it possible to run multiple stages in a parallel branch in a scripted pipeline?
- visual-studio - Visual Studio 2017 - 插入最终换行符
- javascript - How to use the same validation fields in two components?
- google-apps-script - 具有需要合并的多个相同项目的 BOM 脚本
- java - 如果与服务器的连接丢失,使用 Spring Security 是否可以从控制器注销用户