考虑一个字符串有多个点,但我想从第5个点(。)到字符串的末尾读取和显示。您可以建议任何单个选择查询。
例如:
I / P
We.are.inserting.a.lot.of.records by using SSIS Package.even.the.records are.not committed.
o / P
of.records by using SSIS Package.even.the.records are.not committed.
答案 0 :(得分:2)
使用CHARINDEX
,一种方法:
DECLARE @String varchar(500);
SET @String = 'We.are.inserting.a.lot.of.records by using SSIS Package.even.the.records are.not committed.';
SELECT STUFF(@string, 1, CI5.CI,'')
FROM (VALUES(CHARINDEX('.',@String))) CI1(CI)
CROSS APPLY (VALUES(CHARINDEX('.',@String, CI1.CI+1))) CI2(CI)
CROSS APPLY (VALUES(CHARINDEX('.',@String, CI2.CI+1))) CI3(CI)
CROSS APPLY (VALUES(CHARINDEX('.',@String, CI3.CI+1))) CI4(CI)
CROSS APPLY (VALUES(CHARINDEX('.',@String, CI4.CI+1))) CI5(CI);
返回:'of.records by using SSIS Package.even.the.records are.not committed.'
答案 1 :(得分:1)
您可以拨打recursice CTE进行救援:
DECLARE @yourString NVARCHAR(MAX)='We.are.inserting.a.lot.of.records by using SSIS Package.even.the.records are.not committed.';
DECLARE @CountDots INT=5;
WITH recCTE AS
(
SELECT @yourString AS Original
,CHARINDEX('.',@yourString) AS PosDot
,1 AS DotCount
UNION ALL
SELECT r.Original
,CHARINDEX('.',@yourString,r.PosDot+1)
,r.DotCount+1
FROM recCTE AS r
WHERE r.DotCount<@CountDots
)
SELECT SUBSTRING(@yourString,(SELECT MAX(PosDot) FROM recCTE)+1,LEN(@yourString))
一个优点是您可以动态定义点数。另一个优点是您可以将其完全内联到任何查询,VIEW或iTVF。
DECLARE @yourStringTable TABLE(ID INT IDENTITY,SomeString NVARCHAR(MAX));
INSERT INTO @yourStringTable VALUES
('We.are.inserting.a.lot.of.records by using SSIS Package.even.the.records are.not committed.')
,('1.2.3.4.5.6.7.8');
DECLARE @CountDots INT=5;
WITH recCTE AS
(
SELECT ID
,SomeString AS Original
,CHARINDEX('.',SomeString) AS PosDot
,1 AS DotCount
FROM @yourStringTable
UNION ALL
SELECT r.ID
,r.Original
,CHARINDEX('.',r.Original,r.PosDot+1)
,r.DotCount+1
FROM recCTE AS r
WHERE r.DotCount<@CountDots
)
SELECT ID
,Original
,SUBSTRING(Original,(SELECT MAX(x.posDot) FROM recCTE AS x WHERE x.ID=recCTE.ID)+1,LEN(Original))
FROM recCTE
WHERE PosDot=(SELECT MAX(x.posDot) FROM recCTE AS x WHERE x.ID=recCTE.ID)
答案 2 :(得分:1)
嵌套CHARINDEX:
SELECT
STUFF(val,1, charindex('.',val,charindex('.',val,charindex('.',val,charindex('.',
val,charindex('.',val)+1)+1)+1)+1), '')
FROM (values('.2.3.4.5.6.7'),('2.3.4.5.6.7'),('abc')) x(val)
当字符串不包含5个点时,这将返回整个字符串。
答案 3 :(得分:0)
对于上述字符串值,只有patindex()
函数足以在dot(.)s
substring()
函数<{1}}之后读取字符串
select
substring(I/P, patindex('%[.A-Z].[A-Z][.A-Z].[A-Z]%', I/P)+2, LEN(I/P)) [O/P]
from table