我目前正在使用下面列出的函数来查找2个字符串之间的文本,我的问题是找不到任何内容它只返回错误而我不会返回空格或Null,任何人都可以提供有关如何的任何建议请改变它。?
CREATE FUNCTION [dbo].[udf_GetStringBetween2Strings]
(
@String varchar(max),
@FirstString varchar(256),
@SecondString varchar(256)
)
RETURNS VARCHAR(max)
AS
BEGIN
DECLARE @FirstPosition int, @SecondPosition int
SET @FirstPosition = CHARINDEX(@FirstString,@String) + LEN(@FirstString)
SET @SecondPosition = CHARINDEX(@SecondString,@String)
RETURN (SELECT SUBSTRING(@String, @FirstPosition, @SecondPosition - @FirstPosition))
END
答案 0 :(得分:0)
试试这个
CREATE FUNCTION [dbo].[udf_GetStringBetween2Strings]
(
@String varchar(max),
@FirstString varchar(256),
@SecondString varchar(256)
)
RETURNS VARCHAR(max)
AS
BEGIN
DECLARE @FirstSplit VARCHAR(100),@SecondSplit VARCHAR(100),@ReturnStr VARCHAR(100)
SET @FirstSplit = SUBSTRING(@String,0,CHARINDEX(' ',@String))
SET @String = SUBSTRING(@String,CHARINDEX(' ',@String)+1,LEN(@String))
SET @SecondSplit = @String
IF @FirstSplit = @FirstString
SET @ReturnStr = @FirstSplit
ELSE IF @SecondSplit = REPLACE(@SecondString,'?','')
SET @ReturnStr = @SecondSplit
ELSE
SET @ReturnStr = 'Not Found' RETURN @ReturnStr END
答案 1 :(得分:0)
最直接的方法是检查charindex的结果(当找不到匹配时返回0)。 e.g。
DECLARE @FirstPosition int, @SecondPosition int
SET @FirstPosition = CHARINDEX(@FirstString,@String)
if @FirstPosition = 0 return 'Not found'
set @FirstPosition += LEN(@FirstString)
SET @SecondPosition = CHARINDEX(@SecondString,@String, @FirstPosition)
if @SecondPosition = 0 return 'Not found'
return SUBSTRING(@String, @FirstPosition, @SecondPosition - @FirstPosition)