CREATE TABLE AccountPolicies (
account_nbr INT,
policy VARCHAR(20),
PRIMARY KEY (account_nbr, policy));
INSERT INTO AccountPolicies VALUES(1, 'P1000234');
INSERT INTO AccountPolicies VALUES(1, 'P1020256');
INSERT INTO AccountPolicies VALUES(2, '1001');
INSERT INTO AccountPolicies VALUES(2, '5002');
INSERT INTO AccountPolicies VALUES(2, '50001');
INSERT INTO AccountPolicies VALUES(2, '50005');
INSERT INTO AccountPolicies VALUES(2, 'P50005');
-- Second predicate may be evaluated first
-- resulting in conversion error
SELECT account_nbr, policy
FROM AccountPolicies
WHERE account_nbr = 2
AND CAST(policy AS INT) > 50000;
-- The derived table is expended in the
-- query plan and predicates can be pushed
-- up or down in the plan
SELECT account_nbr, policy
FROM (SELECT account_nbr, policy
FROM AccountPolicies
WHERE account_nbr = 2) AS P
WHERE CAST(policy AS INT) > 50000;
-- Enforce sequence of evaluating conditions
-- and cast only valid values
SELECT account_nbr, policy
FROM AccountPolicies
WHERE CASE
WHEN account_nbr = 2
THEN CASE
WHEN policy NOT LIKE '%[^0-9]%'
THEN CASE
WHEN CAST(policy AS INT) > 50000
THEN 'True'
ELSE 'False'
END
ELSE 'False'
END
ELSE 'False'
END = 'True';
Labels: t-sql programming