如何根据条件创建返回不同结果集的T-SQL语句(IF语句)

时间:2014-04-19 01:32:00

标签: sql sql-server if-statement case-when

SQL,我创建了一个SP,它将根据通过条件返回结果集,我尝试了这个语句

CREATE PROCEDURE [dbo].[GetAllMerchandise]
    @param varchar(50)
AS
BEGIN
    SELECT CASE WHEN @param = 'Regular' THEN
        SELECT id, lookup_code,item_name,regular_price 
             FROM dbo.vwMenuAndItemLookup ORDER By item_name ASC
    WHEN @param = 'Promo' THEN
        SELECT id, lookup_code,item_name,promo_price 
            FROM dbo.vwMenuAndItemLookup ORDER By item_name ASC
    WHEN @param = 'Employee' THEN
        SELECT id, lookup_code,item_name,employee_price 
            FROM dbo.vwMenuAndItemLookup ORDER By item_name ASC
    WHEN @param = 'Custom' THEN
        SELECT id, lookup_code,item_name,custom_price 
            FROM dbo.vwMenuAndItemLookup ORDER By item_name ASC
    END
END

但没有运气,你能事先帮助我们吗? 回答最受赞赏的例子。

2 个答案:

答案 0 :(得分:3)

您不希望设置不同的结果,只需要一个不同的列......

SELECT id, lookup_code,item_name,
    CASE WHEN @param = 'Regular' THEN regular_price
         WHEN @param = 'Promo' THEN promo_price
         WHEN @param = 'Employee' THEN employee_price
         WHEN @param = 'Customer' THEN custom_price        
    END as thePrice
    FROM dbo.vwMenuAndItemLookup ORDER By item_name ASC

答案 1 :(得分:1)

CASE WHEN ......那么...... ELSE ... END构造仅适用于单个表达式,而不适用于整个结果集。看起来你希望结果集看起来一样,但只是改变价格列的价值 - 你可以这样做:

CREATE PROCEDURE [dbo].[GetAllMerchandise] @param varchar(50)
AS
BEGIN 
    SELECT id, lookup_code, item_name,
        CASE WHEN @param = 'Regular' THEN regular_price
             WHEN @param = 'Promo' THEN promo_price
             WHEN @param = 'Employee' THEN employee_price
             WHEN @param = 'Custom' THEN custom_price END AS price
    FROM dbo.vwMenuAndItemLookup
    ORDER By item_name ASC
END