Reputation: 7260
I want to print the one of the following condition string if it contains only number field.
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'''
Note: The condition string is dynamic may comes with any number of fields but I want print it only if it contain number.
Expected Result: From the given condition2 should be print.
Number = '12908,13232323'
Upvotes: 0
Views: 54
Reputation: 1051
Using Like to find 'Number' without 'AND'.
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'''
Query
Select conditions From (Values (@Condition),(@Condition1),(@Condition2)) c(conditions)
Where conditions Like '%Number%' And conditions Not Like '%AND%'
Upvotes: 1
Reputation: 7260
Tried the following and does the job done.
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
Upvotes: 0
Reputation: 2729
I use a cte split function
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
This was then leveraged against your data to identify number of conditions in each string, and then filter.
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='
Could do with some more tweaking to exclude outlying cases but hopefully this will get you started.
Upvotes: 2