0
create table policies
(
  policyno varchar(15)
);

insert into policies values ('500'),('501'),('502'),('503');

Declare @PolicyNos varchar(1500) = '500|503';    

SELECT * FROM policies
WHERE policyno = ALL(SELECT item from dbo.fnSplit(@PolicyNos,'|'));

User is going to input multiple policies from front end and application sending multiple policies pipe separated as in @PolicyNos variable.

I'm using split function provided here https://stackoverflow.com/a/337752/435559 to check if all policies in @PolicyNos must exists then return true if any one exists but not the other then return false.

I Tried IN and EXISTS but they do OR operation inside but I want AND every policy exists then return true else false.

Edit -- Added In exists code which I tried

SELECT * FROM policies
WHERE policyno IN (SELECT item from dbo.fnSplit(@PolicyNos,'|'));

SELECT * FROM policies
WHERE exists (SELECT item from dbo.fnSplit(@PolicyNos,'|') where item = policies.policyno);
Community
  • 1
  • 1
Vishwanath Dalvi
  • 35,388
  • 41
  • 123
  • 155

2 Answers2

1

You can do this using conditional aggregation:

WITH vals(val) as (
      SELECT item
      FROM dbo.fnSplit(@PolicyNos,'|')
     )
SELECT (CASE WHEN COUNT(DISTINCT v.val) = COUNT(DISTINCT p.policyno) THEN 'true'
             ELSE 'false'
        END)
FROM vals v left join
     policies p
     ON v.val = p.policyno
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
  • I'm checking for all elements existence so inner join would be fine I feel, why Left join? – Vishwanath Dalvi Nov 26 '14 at 03:37
  • @mr_eclair . . . An inner join would filter rows from both tables, so you would not find policies in `vals` that don't match. – Gordon Linoff Nov 26 '14 at 03:49
  • But then it might need to be a full join, or non-matching policies from the input would be ignored (don't know if they should). And then you would probably also need to compare to `count(*)`. – Andriy M Nov 28 '14 at 18:56
0

I might not have quite understood your question but you could find invalid policy codes with

SELECT item AS invalidPolicy
FROM dbo.fnSplit(@PolicyNos,'|') 
WHERE NOT EXISTS (
    SELECT * 
    FROM policies 
    WHERE item = policies.policyno
)

if you need a conditional

IF EXISTS (
    SELECT item AS invalidPolicy
    FROM dbo.fnSplit(@PolicyNos,'|') 
    WHERE NOT EXISTS (
        SELECT * 
        FROM policies 
        WHERE item = policies.policyno
    )
) BEGIN
     .....
END
ELSE BEGIN
     ......
END
Dave Manning
  • 820
  • 4
  • 11