仅检查字符串中存在的特定字段

时间:2019-02-09 10:04:20

标签: sql-server sql-server-2008-r2

如果要包含以下 only 数字字段,我要打印以下条件字符串之一。

DECLARE @Condition varchar(max) = 'Number =''12908,13232323,12122'' AND Name=''Mak'''

DECLARE @Condition1 varchar(max) = 'Address=''UK'' AND Number =''12908'' AND Name=''Mak'''

DECLARE @Condition2 varchar(max) = 'Number =''12908,13232323'''

注意:条件字符串是动态的,可能带有任意多个字段,但是我只想在包含数字的情况下打印它。

预期结果:应在给定的条件下打印2。

Number = '12908,13232323'

3 个答案:

答案 0 :(得分:2)

我使用cte split功能

CREATE function [dbo].[fn_string_split](@str NVARCHAR(MAX)
, @delimiter NVARCHAR(255))
returns table
as
return
WITH a AS(
        SELECT CAST(0 AS BIGINT) as idx1,CHARINDEX(@delimiter,@str) idx2
        UNION ALL
        SELECT idx2+1,CHARINDEX(@delimiter,@str,idx2+1)
        FROM a
        WHERE idx2>0
    )
    SELECT SUBSTRING(@str,idx1,COALESCE(NULLIF(idx2,0),LEN(@str)+1)-idx1) as value, row_number() over (Order by idx1) RN
    FROM a

然后将其用于您的数据以识别每个字符串中的条件数量,然后进行过滤。

DECLARE @Condition varchar(max) = 'Number =''12908,13232323,12122'' AND Name=''Mak'''

DECLARE @Condition1 varchar(max) = 'Address=''UK'' AND Number =''12908'' AND Name=''Mak'''

DECLARE @Condition2 varchar(max) = 'Number =''12908,13232323'''

DECLARE @Table AS TABLE (ID INT, Condition varchar(MAX))
INSERT INTO @Table VALUES
(0,@Condition),(1,@Condition1),(2,@Condition2);

WITH CTE AS (
SELECT T.*, C.value,COUNT(1) OVER (PARTITION BY ID) Cnt
FROM @Table T
CROSS APPLY dbo.fn_string_split(Condition,'AND') C 
)
SELECT * FROM cte WHERE Cnt=1 AND LEFT(REPLACE(value,' ',''),7) = 'Number='

可以做一些进一步的调整以排除异常情况,但希望这可以帮助您入门。

答案 1 :(得分:1)

使用“ Like”查找不带“ AND”的“ Number”。

DECLARE @Condition varchar(max) = 'Number =''12908,13232323,12122'' AND Name=''Mak'''
DECLARE @Condition1 varchar(max) = 'Address=''UK'' AND Number =''12908'' AND Name=''Mak'''
DECLARE @Condition2 varchar(max) = 'Number =''12908,13232323'''

查询

Select conditions From (Values (@Condition),(@Condition1),(@Condition2)) c(conditions)
Where conditions Like '%Number%' And conditions Not Like '%AND%'

答案 2 :(得分:0)

尝试以下操作并完成工作。

DECLARE @Condition varchar(max) = 'Number =''12908,13232323,12122'' AND Name=''Mak'''

DECLARE @Condition1 varchar(max) = 'Address=''UK'' OR Number =''12908'' AND Name=''Mak'''

DECLARE @Condition2 varchar(max) = 'Number =''12908,13232323'''

IF REPLACE(REPLACE(@Condition,' OR ',' @ '),' AND ',' @ ') NOT LIKE '%@%' 
BEGIN
    PRINT(@Condition);
END
ELSE IF REPLACE(REPLACE(@Condition1,' OR ',' @ '),' AND ',' @ ') NOT LIKE '%@%' 
BEGIn
    PRINT(@Condition1);
END
ELSE IF REPLACE(REPLACE(@Condition2,' OR ',' @ '),' AND ',' @ ') NOT LIKE '%@%'  
BEGIn
    PRINT(@Condition2);
END
ELSE
BEGIN
    PRINT('none');
END