Hello SQL Server experts. Please help me with the efficient way to apply boolean logic (And, Or) to a comma-separated input string in SQLsServer.
Example:
DECLARE @ATable TABLE(ID INT, Value varchar(50))
INSERT INTO @ATable
VALUES (1, 'A'), (1, 'B'), (1, 'C'), (2, 'C'), (2, 'D'), (3, 'A'), (4, 'B')
declare @inputStr varchar(max)
set @inputStr = 'A,B,C,D'
declare @andOr varchar(30) -- can be either 'and' or 'or'
if @andOr = 'and'
, I would like to get Ids that have values both A and B. In above table the result would be data with Id 1. So the result would be
ID | Values
-----------
1 | A,B,C
if @andOr = 'or'
, I would like to get Ids that have values either A or B. In above table the result would be data with Id 1,3 and 4. So the result would be
ID | Values
-----------
1 | A,B,C
3 | A
4 | B
Thanks.
Please test following SQL Select statements
The first thing you should pay attention is the SQL string split function You can create a copy of the user defined split function on your database
I use COUNT() aggregate function with Partition By clause. This is also a great enhancement in T-SQL for programmers. I use this to check if all input parameter string pieces match with @ATable values
The last trick is string concatenation in SQL for display. I used "For XML Path" for string concatenation to fulfill your requirement
DECLARE @ATable TABLE(ID INT, Value varchar(50))
INSERT INTO @ATable VALUES (1,'A'),(1,'B'),(1,'C'),(2,'C'),(2,'D'),(3,'A'),(4,'B')
declare @inputStr varchar(max)
set @inputStr='A,B'
declare @andOr varchar(30)
set @andOr='and'
SELECT
t.ID,
STUFF(
(
SELECT ',' + t1.Value
FROM @ATable t1
WHERE t1.ID = t.ID
FOR XML PATH(''),TYPE
).value('.','VARCHAR(MAX)'
), 1, 1, '') as [Values]
FROM (
select
distinct ID
from (
select
s.cnt, t.*,
tcount = count(t.value) over (partition by t.id)
from (
select *, cnt = count(*) over (partition by 1) from dbo.split(@inputStr,',') s
) s
left join @ATable t on s.val = t.value
) r
where tcount = cnt
) t
set @andOr='or'
SELECT
t.ID,
STUFF(
(
SELECT ',' + t1.Value
FROM @ATable t1
WHERE t1.ID = t.ID
FOR XML PATH(''),TYPE
).value('.','VARCHAR(MAX)'
), 1, 1, '') as [Values]
FROM (
select
distinct t.ID
from dbo.split(@inputStr,',') s
inner join @ATable t on s.val = t.value
) t
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.