是否有一种简短的方法可以将字符串中的int值分开,例如" john 15 doe 1988"
我正在构建全文搜索查询,并且无法将int字段添加到目录中,也无法使用视图,因为查询包含XML字段。
我必须构建一个我可以查询的SQL,如
ID IN (15, 1988)
或
ID = 15 OR ID = 1988
我目前的代码是用空格字符分隔每个单词。
DECLARE @SearchTerm NVARCHAR(MAX)
DECLARE @Pos INT
DECLARE @Len INT
DECLARE @Word NVARCHAR(MAX)
DECLARE @SQL NVARCHAR(MAX)
SET @SearchTerm = 'john 15 doe 1988'
SET @SearchTerm = RTRIM(LTRIM(@SearchTerm))
SET @Pos = 0
SET @Len = 0
IF LEN(@SearchTerm) > 0
BEGIN
--Add space as last char if not space
IF(CHARINDEX(' ', @SearchTerm, LEN(@SearchTerm) - 1) = 0)
SET @SearchTerm = @SearchTerm + ' '
WHILE CHARINDEX(' ', @SearchTerm, @Pos+1)>0
BEGIN
SET @Len = CHARINDEX(' ', @SearchTerm, @Pos+1) - @Pos
SET @Word = CAST(SUBSTRING(@SearchTerm, @Pos, @Len) AS NVARCHAR(MAX))
PRINT @Word
SET @SQL = @SQL + 'FORMSOF(INFLECTIONAL, ' + @Word + ') OR'
SET @Pos = CHARINDEX(' ', @SearchTerm, @Pos+@Len) + 1
END
END
请注意,查询应该支持SQL Server 2008,我不能使用TRY_PARSE()
答案 0 :(得分:0)
您可以使用ISNUMERIC来确定表达式是否为有效的数字类型。
当输入表达式求值为有效的数值数据类型时,ISNUMERIC返回1;否则返回0
IF ISNUMERIC(@Word) = 1 SET @SQLIDs = @SQLIDs + @Word + ', '
答案 1 :(得分:0)
好问题。我坐得无聊。我只是尝试了自己的方式。试一试。发布在这里
DECLARE @str VARCHAR(200);
DECLARE @output VARCHAR(200);
DECLARE @letter VARCHAR(1);
DECLARE @pos INT
DECLARE @length INT
DECLARE @preSpace INT = 0
CREATE TABLE #Final (value INT)
SET @pos = 1
SET @output = ''
SET @str = 'john 15 doe 1988 testing 6 768 i955 99 my pretty 74j4'
SELECT @length = len(@str)
WHILE (@pos <= @length)
BEGIN
SELECT @letter = SUBSTRING(@str, @pos, 1)
IF EXISTS (
SELECT 1
WHERE @letter IN (
'1'
,'2'
,'3'
,'4'
,'5'
,'6'
,'7'
,'8'
,'9'
,'0'
,' '
)
)
BEGIN
IF (
@letter = CHAR(32)
AND @output <> ''
AND @preSpace = 0
)
BEGIN
SET @preSpace = 1
INSERT INTO #Final
VALUES (@output)
SET @output = ''
END
ELSE
BEGIN
SET @preSpace = 0
SET @output = @output + '' + CAST(@letter AS VARCHAR) + ''
END
END
SET @pos = @pos + 1
END
IF (@output <> '')
INSERT INTO #Final
VALUES (@output)
SET @output = ''
SELECT *
FROM #Final
DROP TABLE #Final