gpt4 book ai didi

sql-server - 从表中的字符串中获取最后一个单词

转载 作者:行者123 更新时间:2023-12-04 12:10:45 26 4
gpt4 key购买 nike

我试图从表 Project 中得到最后一个词在 SQL Server 2017 中。

我的代码如下:

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

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

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

Invalid length parameter passed to the LEFT or SUBSTRING function.



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

最佳答案

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

无需拆分字符串。您的错误仅仅是因为 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

关于sql-server - 从表中的字符串中获取最后一个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58438406/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com