2017-02-09 77 views
0

我有一個標量值如何將SQL Server中的單詞聚合在一起?

八萬七千九百八十九

我怎樣才能使它七八十一千九百八十九

到目前爲止,我已經能夠找到發生的位置,但之後我迷路了

with cte as 
(select 'Eighty Thousand and Seven Thousand and Nine Hundred and Eighty Nine' as name 
), 
pos as 
(select patindex('%Thousand%',name) pos, name from cte 
union all 
select pos+patindex('%Thousand%',substring(name, pos+1, len(name))) pos, name from pos 
where patindex('%Thousand%',substring(name, pos+1, len(name)))>0 
) 
select pos from pos 

提前致謝。

+1

猜測:分裂的「和」,並轉換每一部分爲數字(八萬= 80000),再加入所有與結果轉換爲文本。雖然這將在「七八萬」上失效 - 780000) –

+0

您可能會更好地將字符串解析爲整數值,然後將整數轉換爲您最喜歡的散文風格。您的單個示例可以在「和」處被分解並且每個片段被轉換和求和。 – HABO

回答

0

Declare @String1 varchar(100) Declare @String2 varchar(100) declare @string nvarchar(264) 
 
set @string = N'Eighty Thousand and Seven Thousand and Nine Hundred and Eighty Nine'; 
 
-- Ensure it ends with a space 
 
SET @string = @string + ' '; 
 
WITH cte (Id, Value, Rest) 
 
AS (SELECT 1 as Id,SUBSTRING(@string, 1, CHARINDEX(' ', @string, 1) - 1) AS Value ,SUBSTRING(@string, CHARINDEX(' ', @string, 1) + 1, LEN(@string)) AS Value 
 
    UNION ALL SELECT Id + 1 AS Id,SUBSTRING(Rest, 1, CHARINDEX(' ', Rest, 1) - 1) AS Value,SUBSTRING(Rest, CHARINDEX(' ', Rest, 1) + 1, LEN(Rest)) AS Value FROM cte WHERE CHARINDEX(' ', Rest, 1) <> 0) 
 

 
SELECT @String1= Value 
 
FROM cte 
 
WHERE id = 2; -- = 2rd word to get 
 
WITH cte1 (Id, Value, Rest) 
 
AS (SELECT 1 as Id,SUBSTRING(@string, 1, CHARINDEX(' ', @string, 1) - 1) AS Value ,SUBSTRING(@string, CHARINDEX(' ', @string, 1) + 1, LEN(@string)) AS Value 
 
    UNION ALL SELECT Id + 1 AS Id,SUBSTRING(Rest, 1, CHARINDEX(' ', Rest, 1) - 1) AS Value,SUBSTRING(Rest, CHARINDEX(' ', Rest, 1) + 1, LEN(Rest)) AS Value FROM cte1 WHERE CHARINDEX(' ', Rest, 1) <> 0) 
 
SELECT @String2 =Value 
 
FROM cte1 
 
WHERE id = 5; -- = 5rd word to get 
 
IF @[email protected] 
 
Begin set @string = Replace(Replace(@string,'Thousand and',''),' ',' ') Print @string 
 
END