我正在尋找一串單詞中的幾個字母。所以它應該是前 5 個字符(如果沒有超過 5 個字符,那么整個單詞和接下來的單詞 5 1( 1...)
例如,關鍵客戶銷售我只想得到“KeyAS”或 HR General - HRG
我目前正在使用這個
ALTER FUNCTION [dbo].[fnFirsties5]
(
@str NVARCHAR(4000)
)
RETURNS NVARCHAR(2000)
AS
BEGIN
DECLARE retval NVARCHAR(2000);
SET str=RTRIM(LTRIM(@str));
SET retval=LEFT(@str,5);
WHILE CHARINDEX(' ',@str,1) > 0 BEGIN
SET str=LTRIM(RIGHT(@str,LEN(@str)-CHARINDEX(' ',@str,1)));
SET retval =LEFT(@str,1);
END
RETURN retval;
END –
但這給出了“Key AAS”或“HR GeG”的結果
還有幾點需要注意
版本 - Microsoft SQL Server 2008 R2 (SP3-GDR) (KB4057113) - 10.50.6560.0 (X64) 2017 年 12 月 28 日 15:03:48 著作權所有 (c) Windows NT 6.0(內部版本 6002)上的 Microsoft Corporation 標準版(64 位) : Service Pack 2)(管理程式)
目前我得到的
Empl ID Name Job Family Description
123 John Smith Key AAS Key Account Sales
124 karen Smith HR GeG HR General
213 John Doe Production Operator Production Operator
我的期望
Empl ID Name Job Family Description
123 John Smith Key AS Key Account Sales
124 karen Smith HR G HR General
213 John Doe ProduO Production Operator
我目前使用的代碼是
ALTER FUNCTION [dbo].[fnFirsties5] ( @str NVARCHAR(4000) )
RETURNS NVARCHAR(2000)
AS
BEGIN
DECLARE @retval NVARCHAR(2000);
SET @str=RTRIM(LTRIM(@str));
SET @retval=LEFT(@str,5);
WHILE CHARINDEX(' ',@str,1)>0 BEGIN
SET @str=LTRIM(RIGHT(@str,LEN(@str)-CHARINDEX(' ',@str,1)));
SET @retval =LEFT(@str,1);
END
RETURN @retval;
END
謝謝
uj5u.com熱心網友回復:
您通常可以使用STRING_SPLIT()功能來實作這一點。雖然這很粗略,因為STRING_SPLIT()不輸出被拆分的術語的序數。話雖如此,我們可以用CHARINDEX(). 但是請注意,如果輸入字串中重復相同的單詞,則 ordinal 將失敗。不過,這可能仍然為您提供一條前進的道路:
CREATE TABLE t1 (s1 VARCHAR(500));
INSERT INTO t1 VALUES ('This Is A Test');
INSERT INTO t1 VALUES ('And Another Test');
INSERT INTO t1 VALUES ('Key Account Sales');
SELECT
s1,
SUBSTRING(STRING_AGG(CASE WHEN rn = 1 THEN SUBSTRING(value, 1, 5) ELSE SUBSTRING(value, 1, 1) END, ''), 1, 5) as output
FROM
(
SELECT
s1,
value,
ROW_NUMBER() OVER (PARTITION BY s1 ORDER BY CHARINDEX(value, s1, 1)) as rn
FROM t1
CROSS APPLY STRING_SPLIT(s1, ' ')
) sub
GROUP BY s1
------------------- --------
| s1 | output |
------------------- --------
| And Another Test | AndAT |
| Key Account Sales | KeyAS |
| This Is A Test | ThisI |
------------------- --------
uj5u.com熱心網友回復:
如果我了解要求
Declare @YourTable table (SomeCol varchar(50))
Insert into @YourTable Values
('Key Account Sales')
,('HR General')
,('Customer Support Group')
Select SomeCol
,NewValue = concat( left(JSON_VALUE(S,'$[0]'),5)
,left(JSON_VALUE(S,'$[1]'),1)
,left(JSON_VALUE(S,'$[2]'),1)
,left(JSON_VALUE(S,'$[3]'),1)
,left(JSON_VALUE(S,'$[4]'),1)
,left(JSON_VALUE(S,'$[5]'),1)
,left(JSON_VALUE(S,'$[6]'),1) -- Expand if more than 7 words
)
From @YourTable A
Cross Apply ( values ( '["' replace(string_escape(SomeCol,'json'),' ','","') '"]' ) ) B(S)
結果
SomeCol NewValue
Key Account Sales KeyAS
HR General HRG
Customer Support Group CustoSG
編輯 - 如果你想要一個函式
CREATE Function [dbo].[YourFunction] (@S varchar(150))
Returns varchar(50)
Begin
Return (
Select concat( left(JSON_VALUE(S,'$[0]'),5)
,left(JSON_VALUE(S,'$[1]'),1)
,left(JSON_VALUE(S,'$[2]'),1)
,left(JSON_VALUE(S,'$[3]'),1)
,left(JSON_VALUE(S,'$[4]'),1)
,left(JSON_VALUE(S,'$[5]'),1)
,left(JSON_VALUE(S,'$[6]'),1) -- Expand if more than 7 words
)
From (values ( '["' replace(string_escape(@S,'json'),' ','","') '"]' ) ) A(S)
)
End
用法
Select [dbo].[YourFunction]('Key Account Sales')
編輯--- 2008 XML 版本
CREATE Function [dbo].[YourFunction] (@S varchar(150))
Returns varchar(50)
Begin
Return (
Select coalesce(xDim.value('/x[1]','varchar(5)'),'')
coalesce(xDim.value('/x[2]','varchar(1)'),'')
coalesce(xDim.value('/x[3]','varchar(1)'),'')
coalesce(xDim.value('/x[4]','varchar(1)'),'')
coalesce(xDim.value('/x[5]','varchar(1)'),'')
coalesce(xDim.value('/x[6]','varchar(1)'),'')
coalesce(xDim.value('/x[7]','varchar(1)'),'')
From ( values (cast('<x>' replace((Select replace(@S,' ','§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>') '</x>' as xml))) as A(xDim)
)
End
用法
Select [dbo].[YourFunction]('Key Account Sales')
uj5u.com熱心網友回復:
還有一個非常彈性的V2008運行方式(你真的應該升級...)
--宣告的表變數中的一些測驗值
DECLARE @input TABLE(YourString VARCHAR(1000))
INSERT INTO @input VALUES('Key Account Sales')
,('HR General')
,('Production Operator')
,('') --test edge cases
,(NULL)
,('a b c d e f g')
,('Some incredibly long and stupid text to test even this');
--查詢(借用FROM(VALUES(約翰的回答)
SELECT xDim.query(N'(
<itm>{substring(concat((/x[@pos=1]/text())[1]," "),1,5)}</itm>
,for $rest in /x[empty(@pos)]
return
<itm>{substring(($rest/text())[1],1,1)}</itm>
)
').value('.','nvarchar(max)')
FROM @input i
CROSS APPLY(VALUES(CAST('<x pos="1">' REPLACE((SELECT REPLACE(i.YourString,' ','§§Split§§') AS [*] FOR XML PATH('')),'§§Split§§','</x><x>') '</x>' AS XML))) as A(xDim);
- 結果
Key AS
HR G
ProduO
a bcdefg
Some ilastttet
簡而言之的想法
- 我使用與 John Cappelletti 所做的相同的方法 (XML) 創建一個 XML,其中每個單詞都存在于它自己的元素中。
- 除了約翰,我補充
pos="1"了第一個<x> - 現在我們可以使用
XQuery - 第一步是從第一個單詞中挑出5個字符(注意:我在剪5個之前加了一個空格)
- XQuery-
for將遍歷其余的 ( no@pos) 并附加第一個字符。 - final
.value只會將所有資料作為字串獲取。
提示:upper-case()在 XQuery 中有助于獲取單個字符“大”...
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/359859.html
標籤:sql sql-server 查询语句
下一篇:SQL中的模式匹配和資料整理
