我正在玩构建一个sql函数,它将从标题中提取数字,这就是下面的代码所做的。虽然,我想修改此函数以将数字解析为部分。例如:
标题栏中的当前数据:
QW 1 RT 309-23-1 QW 1 RT 29-1 QW 1 RT 750-1 QW RT 750-1
在标题字段上运行一次创建的临时表:
column 1 Column 2 Column 3 Column 4 1 309 23 1 1 29 1 Null 1 750 1 Null Null 750 1 Null
create function [dbo].[ExtractNumbers](@Numbers nvarchar(2000))
returns nvarchar(2000)
as
BEGIN
declare @NonNumericIndex int
set @NonNumericIndex = PATINDEX('%[^0-9]%',@Numbers)
WHILE @NonNumericIndex > 0
begin
SET @Numbers = REPLACE(@Numbers,SUBSTRING(@Numbers,@NonNumericIndex,1),'')
SET @NonNumericIndex = PATINDEX('%[^0-9]%',@Numbers)
SET
end
return @Numbers
END
答案 0 :(得分:0)
这是一种方式。
虽然实际上最后我意识到格式比我原先实现的更加固定,所以你最好只使用各种字符串操作函数来直接计算列。
WITH TestTable AS
(
SELECT 'QW 1 RT 309-23-1' AS title UNION ALL
SELECT 'QW 1 RT 29-1' UNION ALL
SELECT 'QW 1 RT 750-1' UNION ALL
SELECT 'QW RT 750-1'
)
SELECT title, [1] AS [Column 1], [2] AS [Column 2],[3] AS [Column 3],[4] AS [Column 4]
FROM TestTable CROSS APPLY dbo.GetNumbers(title)
PIVOT
(MAX(num) FOR idx IN ([1], [2],[3],[4])
) AS PivotTable;
使用以下TVF
CREATE FUNCTION GetNumbers
(
@Numbers NVARCHAR(2000)
)
RETURNS @Results TABLE
(
idx INT IDENTITY(1,1),
num INT
)
AS
BEGIN
DECLARE @NonNumericIndex INT, @NumericIndex INT
SET @NumericIndex = PATINDEX('%[0-9]%',@Numbers)
IF (@NumericIndex > 4) --First Column not there
INSERT INTO @Results VALUES (NULL)
WHILE @NumericIndex > 0
BEGIN
SET @Numbers = RIGHT(@Numbers,LEN(@Numbers)-@NumericIndex+1)
SET @NonNumericIndex = PATINDEX('%[^0-9]%',@Numbers)
IF(@NonNumericIndex = 0)
BEGIN
INSERT
INTO @Results VALUES (@Numbers)
RETURN
END
ELSE
INSERT
INTO @Results VALUES
(LEFT(@Numbers,@NonNumericIndex-1))
SET @Numbers = RIGHT(@Numbers,LEN(@Numbers)-@NonNumericIndex+1)
SET @NumericIndex = PATINDEX('%[0-9]%',@Numbers)
END
RETURN
END