我的数据集正在发生变化,现在我的客户名称字段开头还包含两个额外的单词,我需要在将数据移到主客户表之前清理这些数据。
我需要做的是在select语句中仅保留第二个空格之后的单词。
任何人都可以建议一种方法来做到这一点
即。 " ZENDUSER ABCABC S ROCCO AL PORTO"需要作为" S ROCCO AL PORTO"
返回答案 0 :(得分:2)
您可以使用CHARINDEX和SUBSTRING执行此操作:
declare @a varchar(200)
set @a = 'ZENDUSER ABCABC S ROCCO AL PORTO'
select @a, substring(@a, charindex(' ', @a, charindex(' ', @a, 1) + 1) + 1, 200)
答案 1 :(得分:0)
DECLARE @cust NVARCHAR(MAX);
SET @cust = N'ZENDUSER ABCABC S ROCCO AL PORTO';
SELECT SUBSTRING(@cust, CHARINDEX(' ', @cust, CHARINDEX(' ', @cust, 0) + 1) + 1,
LEN(@cust) - CHARINDEX(' ', @cust, CHARINDEX(' ', @cust, 0) + 1));
GO
| (No column name) |
| :--------------- |
| S ROCCO AL PORTO |
dbfiddle here
答案 2 :(得分:0)
试试这个:
select substring(MyColumn, CHARINDEX(MyColumn, ' ', CHARINDEX(MyColumn, ' ', 1) + 1) + 1, Len(MyColumn)) from MyTable
我知道,这与MJH答案非常类似,但另外,我在Len(MyColumn)
方法中采用substring
,因此我们确信在第二个空格后包含所有字符。另一个答案只需要200个字符。
答案 3 :(得分:0)
如果您希望修剪更加动态,即从第5个字开始等,您可以使用以下代码段。我会将其封装在内联函数中以获得更多功能
DECLARE @Sentence NVARCHAR(200) = 'ZENDUSER ABCABC S ROCCO AL PORTO'
DECLARE @Del NVARCHAR(2)= ' '
DECLARE @WordStart INT = 5
;WITH Nums (n) as
(
SELECT TOP (LEN(@Sentence)) ROW_NUMBER() OVER (ORDER BY (SELECT NULL))
FROM (VALUES (0),(0),(0),(0),(0),(0),(0),(0)) a(n)
CROSS JOIN (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) b(n)
CROSS JOIN (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) c(n)
CROSS JOIN (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) d(n)
)
, Main as
(
SELECT N, x.val , Ind , CASE WHEN n = 1 THEN 1 ELSE SUM(Ind) OVER (ORDER BY n) + 1 END Pos
FROM Nums
CROSS APPLY
(
VALUES (SUBSTRING(@Sentence,n,1),
CASE WHEN SUBSTRING(@Sentence,n,1) = @Del THEN 1 ELSE 0 END)
) x(val, Ind)
)
, Combine (StrOut) as
(
SELECT LTRIM(RTRIM(STUFF(
CAST((SELECT ''+ val
FROM Main
WHERE Pos >= @WordStart
FOR XML PATH (''),TYPE) AS NVARCHAR(MAX)),1,0,'')
)))
SELECT StrOut
FROM Combine
更新:创建功能
CREATE FUNCTION dbo.SentenceSplitter
(
@Sentence NVARCHAR(2000),
@WordStart INT,
@Del NVARCHAR(2) = ' '
)
RETURNS TABLE AS RETURN
WITH Nums (n) as
(
SELECT TOP (LEN(@Sentence)) ROW_NUMBER() OVER (ORDER BY (SELECT NULL))
FROM (VALUES (0),(0),(0),(0),(0),(0),(0),(0)) a(n)
CROSS JOIN (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) b(n)
CROSS JOIN (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) c(n)
CROSS JOIN (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) d(n)
)
, Main as
(
SELECT N, x.val , Ind , CASE WHEN n = 1 THEN 1 ELSE SUM(Ind) OVER (ORDER BY n) + 1 END Pos
FROM Nums
CROSS APPLY
(
VALUES (SUBSTRING(@Sentence,n,1),
CASE WHEN SUBSTRING(@Sentence,n,1) = @Del THEN 1 ELSE 0 END)
) x(val, Ind)
)
, Combine (StrOut) as
(
SELECT LTRIM(RTRIM(STUFF(
CAST((SELECT ''+ val
FROM Main
WHERE Pos >= @WordStart
FOR XML PATH (''),TYPE) AS NVARCHAR(MAX)),1,0,'')
)))
SELECT StrOut
FROM Combine
用例:
SELECT StrOut
FROM dbo.SentenceSplitter ('ZENDUSER ABCABC S ROCCO AL PORTO', 5, ' ')
将导致:
StrOut
AL PORTO