2014-02-27 81 views
0

這裏是代碼是否有寫冗長的where子句

DECLARE @List TABLE (n nvarchar(50)); 

INSERT INTO @list (n) VALUES ('A'),('B'),('C'),('D'),('E'); 

SELECT 
    (t1.n) 
    + (t2.n) 
    + (t3.n) 
    + (t4.n) 
    +(t5.n) 
FROM @list AS t1 
JOIN @list AS t2 
    ON 1=1 
JOIN @list AS t3 
    ON 1=1 
JOIN @list AS t4 
    ON 1=1 
JOIN @list AS t5 
    ON 1=1 
WHERE 
    not t1.n = t2.n 
    and not t1.n = t3.n 
    and not t1.n = t4.n 
    and not t1.n = t5.n 
    and not t2.n = t3.n 
    and not t2.n = t4.n 
    and not t2.n = t5.n 
    and not t3.n = t4.n 
    and not t3.n = t5.n 
    and not t4.n = t5.n 

我需要簡化任何短期和簡單的方式where子句像(其中T1.n,T2.n,T3.n ,. T4.n,T5.n不equl對方)

在此先感謝

回答

1

要創建組合(或者是置換?),你可以使用一個CTE。

如:

;with cte as 
(
select n from @list 
union all 
select convert(nvarchar(50),L.n+ cte.n) from @List L 
    inner join cte on charindex(l.n,cte.n)=0 
where LEN(l.n)<5 

) 
    select * from cte where LEN(n)=5 
+0

哇這更是酷感謝 –

3

可以使用,

NOT IN (....)條款

一樣,

where t1.n NOT IN (t2.n, t3.n, t4.n, t5.n) 
and t2.n NOT IN (t3.n , t4.n,t5.n) 
and t3.n NOT IN (t4.n,t5.n) 
+1

感謝您的幫助,我得到了主意,其中t1.n NOT IN(t2.n,t3.n,t3.n,t4.n,t5.n) 和T2。 n不在(t3.n,t4.n,t5.n) 和t3.n不在(t4.n,t5.n) 和t4.n不在(t5.n)但仍然可能使更多更短 –

4

你可以檢查你有多少個不同的值有:

where (
    select count(distinct n) 
    from (values (t1.n), (t2.n), (t3.n), (t4.n), (t5.n)) as ns (n) 
) = 5 

如果您有少於5個不同的值,有些值相等。

SQL Fiddle

+0

謝謝這就是我想要的 –