案例表达式只显示一次

时间:2018-08-29 21:28:18

标签: sql-server

我遇到了一个难于解决的情况:

WHEN @CustomerID = 3 AND @OrderID = 2 AND @Name IN ('Hello') THEN 'Regular'
WHEN @CustomerID = 3 AND @OrderID = 2 AND @Telephone = 1 AND @Name IN ('Hello') THEN 'Business'

如果我有两个语句,它仅返回“ Regular”,但是如果我取出“ Regular”,则显示“ Business”。我在做什么错了?

2 个答案:

答案 0 :(得分:1)

如果您想要一个或两个,则需要是两个单独的列,或者如果您想在单个列中同时包含两个输出:

要么:

case WHEN @CustomerID = 3 AND @OrderID = 2 AND @Name IN ('Hello') THEN 'Regular' end,
case WHEN @CustomerID = 3 AND @OrderID = 2 AND @Telephone = 1 AND @Name IN ('Hello') THEN 'Business' end

或:

WHEN @CustomerID = 3 AND @OrderID = 2 AND @Telephone = 1 AND @Name IN ('Hello') THEN 'Regular, Business' 
WHEN @CustomerID = 3 AND @OrderID = 2 AND @Name IN ('Hello') THEN 'Regular'

答案 1 :(得分:0)

返回的值将是匹配的最早WHEN子句(按文本形式)的THEN表达式的值。

在您的查询中,Second WHEN子句包含First WHEN子句的一部分。这意味着,只要Second为true,First WHEN子句就为true。因此,最早的(First)WHEN子句将返回THEN表达式。

查询1:

SELECT CASE WHEN @CustomerID = 3 AND @OrderID = 2 AND @Name IN ('Hello') THEN 'Regular'
WHEN @CustomerID = 3 AND @OrderID = 2 AND @Telephone = 1 AND @Name IN ('Hello') THEN 'Business' END

查询2:

SELECT CASE WHEN @CustomerID = 3 AND @OrderID = 2 AND @Telephone = 1 AND @Name IN ('Hello') THEN 'Business'
WHEN @CustomerID = 3 AND @OrderID = 2  AND @Name IN ('Hello') THEN 'Regular' END

输入:

@CustomerID INT=3
@OrderID INT = 2
@Name VARCHAR(100)='Hello'
@Telephone INT=1

输出:

Query1 : 'Regular'
Query1 : 'Business'

输入:

@CustomerID INT=3
@OrderID INT = 2
@Name VARCHAR(100)='Hello'
@Telephone INT=0

输出:

Query1 : 'Regular'
Query1 : 'Regular'