我需要根据固定字符长度选择一个子字符串,直到第N个空间。让我解释一下这个问题。
假设我有三个不同的字符串:
如果我从字符串的开头选择20个字符,我依次得到以下子字符串
但是我想要我的子字符串(最多20个字符长)这样
也就是说,我不希望两个空白之间有任何部分单词
请帮我生成查询。
甲骨文:
select substr(substr(MyField,1,20), 1, instr(substr(MyField,1,20), ' ',-1,1))
from MyTable
SQL服务器
SELECT LEFT(MyField, 20 - CHARINDEX (' ' ,REVERSE(LEFT(MyField,20))))
FROM MyTable
对于Oracle(应该可以将其转换为SQLServer,但我不知道SQLServer:
在下面的测试数据中,我又添加了两个示例来测试这是否按需工作。
with
inputs ( str ) as (
select 'Lorem ipsum dolor sit amet, consectetur adipiscing elit' from dual union all
select 'Lorem ipsumdolor sit amet, consectetur adipiscing elit' from dual union all
select 'Loremipsumdolorsitametconsedtetur' from dual union all
select 'Lorem ipsumdolorsit amet, consectetur etc.' from dual union all
select 'Lorem ipsum dolorsitamet, consectetur adipiscing elit' from dual union all
select 'abcdef ghijk lmno' from dual
),
prep ( str, flag, fragment ) as (
select str,
case when length(str) <= 20 or substr(str, 21, 1) = ' ' then 1 end,
substr(str, 1, 20)
from inputs
)
select str,
case flag when 1 then fragment
else substr(fragment, 1, instr(fragment, ' ', -1) - 1) end
as new_str
from prep;
STR NEW_STR
------------------------------------------------------- --------------------
Lorem ipsum dolor sit amet, consectetur adipiscing elit Lorem ipsum dolor
Lorem ipsumdolor sit amet, consectetur adipiscing elit Lorem ipsumdolor sit
Loremipsumdolorsitametconsedtetur
Lorem ipsumdolorsit amet, consectetur etc. Lorem ipsumdolorsit
Lorem ipsum dolorsitamet, consectetur adipiscing elit Lorem ipsum
abcdef ghijk lmno abcdef ghijk lmno
如果SQL服务器,如果你不介意UDF。
Declare @YourTable table (SomeText varchar(500))
Insert Into @YourTable values
('Lorem ipsum dolor sit amet, consectetur adipiscing elit.'),
('Lorem ipsumdolor sit amet, consectetur adipiscing elit'),
('Lorem ipsum dolorsitamet, consectetur adipiscing elit')
Declare @MaxLen int = 20
Select *,Trimmed = [dbo].[udf-Str-TrimToWord](SomeText,@MaxLen)
From @YourTable
返回
SomeText Trimmed
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor
Lorem ipsumdolor sit amet, consectetur adipiscing elit Lorem ipsumdolor
Lorem ipsum dolorsitamet, consectetur adipiscing elit Lorem ipsum
那个UDF
CREATE FUNCTION [dbo].[udf-Str-TrimToWord] (@String varchar(max),@MaxLen int)
Returns varchar(max)
AS
Begin
Return LEFT(@String,@MaxLen-CharIndex(' ' ,Reverse(Left(@String,@MaxLen))))
End