This would do it although it might not be as elegant as you'd like
SELECT c1,c2,c3 FROM [MyTableName] where c1=x
UNION ALL
SELECT c1,c2,c3 FROM [MyTableName] where c3=z
문제
Hitting a record based on multiple where clauses, I would like SQL to return a copy of the row being hit, for every where clause that matches.
c1 | c2 | c3
x y z
x,y,z : Would be return only once with a where c1=x or c3=z
I would like where c1=x or c3=z
, to return, 2 copies of x,y,z
Can this be achieved?
Why?
I am trying to eliminate running multiple queries to get multiples of the same record to do prioritization.
I can and should get two copies of x,y,z if I run two queries, one for c1, and one for c3.
I want these 2 copies of x,y,z by design, but I want to run one query. With my implementation, I will run into situations where I will have to run more than 10 query trips to get what I am after... for one prioritized record.
I would rather run one single query, than 10.
해결책
This would do it although it might not be as elegant as you'd like
SELECT c1,c2,c3 FROM [MyTableName] where c1=x
UNION ALL
SELECT c1,c2,c3 FROM [MyTableName] where c3=z
다른 팁
Already answered, but here is an alternative:
SELECT c1,c2,c3
FROM [MyTableName]
JOIN (VALUES (1),(2)) t(n)
ON (t.n = 1 AND c1 = 'x') OR (t.n = 2 AND c3 = 'z');
SELECT t.*
FROM MyTable t
CROSS APPLY (
VALUES
(c1,'x'),
(c2,'y'),
(c3,'z')
) f(col,val)
WHERE col = val