我试图拆分一个字符串,但是它的数据类型为varchar,因此抛出一个错误,说它无法转换为浮点数。我试过但无法找到解决方案。我怎么能这样做。
(SELECT Value FROM dbo.SplitString('648-44-21001-13764 ', '-') WHERE Position = 3)
答案 0 :(得分:0)
检查你的函数值列返回类型,它似乎是VARCHAR所以你必须显式地将它转换为float:
ALTER FUNCTION [dbo].[SplitString]
(
@String NVARCHAR(4000),
@Delimiter NCHAR(1)
)
RETURNS TABLE
AS
RETURN
(
WITH Split(stpos,endpos)
AS(
SELECT 0 AS stpos, CHARINDEX(@Delimiter,@String) AS endpos
UNION ALL
SELECT endpos+1, CHARINDEX(@Delimiter,@String,endpos+1)
FROM Split
WHERE endpos > 0
)
SELECT 'Position' = ROW_NUMBER() OVER (ORDER BY (SELECT 1)),
'Value' = SUBSTRING(@String,stpos,COALESCE(NULLIF(endpos,0),LEN(@String)+1)-stpos)
FROM Split
)
SELECT CAST((SELECT Value FROM dbo.SplitString('648-44-21001-13764 ', '-') WHERE Position = 3) AS FLOAT)
答案 1 :(得分:0)
Create FUNCTION SplitString
(
@Input NVARCHAR(MAX),
@Character CHAR(1)
)
退货@Output TABLE(
价值NVARCHAR(1000),
位置int
)
如
开始
DECLARE @StartIndex INT,@ EndIndex INT,@ Position int
SET @Position = 0
SET @StartIndex = 1
IF SUBSTRING(@ Input,LEN(@Input) - 1,LEN(@Input))<> @字符
开始
SET @Input = @Input + @Character
END
WHILE CHARINDEX(@Character, @Input) > 0
BEGIN
SET @EndIndex = CHARINDEX(@Character, @Input)
INSERT INTO @Output(Value,Position)
SELECT SUBSTRING(@Input, @StartIndex, @EndIndex - 1),@Position
SET @Input = SUBSTRING(@Input, @EndIndex + 1, LEN(@Input))
set @Position=@Position+1;
END
RETURN
END
GO