DECLARE @t TABLE(s VARCHAR(255));
INSERT @t SELECT 'Mainly Sunny, 13.7°C'
UNION ALL SELECT 'Partly cloudy, 12°C, Humidity 69%, Wind NE 15km/h';
SELECT RIGHT(LEFT(s, CHARINDEX('°', s)-1),
CHARINDEX(' ', REVERSE(LEFT(s, CHARINDEX('°', s)-1)))-1) FROM @t;
因此,作为计算列:
DECLARE @t TABLE
(
s VARCHAR(255),
x AS CONVERT(VARCHAR(255),RIGHT(LEFT(s, CHARINDEX('°', s)-1),
CHARINDEX(' ', REVERSE(LEFT(s, CHARINDEX('°', s)-1)))-1)) PERSISTED
);
INSERT @t SELECT 'Mainly Sunny, 13.7°C'
UNION ALL SELECT 'Partly cloudy, 12°C, Humidity 69%, Wind NE 15km/h';
SELECT s,x FROM @t;
结果:
Mainly Sunny, 13.7°C 13.7
Partly cloudy, 12°C, Humidity 69%, Wind NE 15km/h 12
如果您可能有不包含°
符号的字符串,那么:
DECLARE @t TABLE
(
s VARCHAR(255),
x AS CONVERT(VARCHAR(255), CASE WHEN CHARINDEX('°', s) > 0 THEN
RIGHT(LEFT(s, CHARINDEX('°', s)-1),
CHARINDEX(' ', REVERSE(LEFT(s, CHARINDEX('°', s)-1)))-1) END) PERSISTED
);
INSERT @t SELECT 'Mainly Sunny, 13.7°C'
UNION ALL SELECT 'Partly cloudy, 12°C, Humidity 69%, Wind NE 15km/h'
UNION ALL SELECT 'No weather to report';
SELECT s,x FROM @t;
结果:
Mainly Sunny, 13.7°C 13.7
Partly cloudy, 12°C, Humidity 69%, Wind NE 15km/h 12
No weather to report NULL
(如果你想要别的东西而不是NULL
,我无法想象是什么,你可以ELSE
在CASE
表达式中添加一个。)
此外,为了证明我的解决方案是灵活的,而不引入性能严重的用户定义函数:
DECLARE @SearchString VARCHAR(8000);
SET @SearchString = 'km/h'; -- change this to '°'
DECLARE @t TABLE
(
s VARCHAR(255)
);
INSERT @t SELECT 'Mainly Sunny, 13.7°C'
UNION ALL SELECT 'Partly cloudy, 12°C, Humidity 69%, Wind NE 15km/h'
UNION ALL SELECT 'No weather to report'
UNION ALL SELECT 'Wind 102km/h, 23.5°C, mostly cloudy';
SELECT s, x = CONVERT(VARCHAR(255), CASE WHEN CHARINDEX(@SearchString, s) > 0 THEN
RIGHT(LEFT(s, CHARINDEX(@SearchString, s)-1),
CHARINDEX(' ', REVERSE(LEFT(s, CHARINDEX(@SearchString, s)-1)))-1) END)
FROM @t;
结果:
Mainly Sunny, 13.7°C NULL
Partly cloudy, 12°C, Humidity 69%, Wind NE 15km/h 15
No weather to report NULL
Wind 102km/h, 23.5°C, mostly cloudy 102