仅计数和由sp参数控制的排序

时间:2016-02-12 18:39:35

标签: sql sql-server tsql sql-server-2012

我在存储过程中有一个非常复杂的查询,它获取id的列表,然后返回由两个参数控制的不同内容:

@count_only [bit]
@order_type [tinyint]

因此,如果@count_only1,则查询应该只返回结果计数,否则它应该返回根据@order_type值排序的id列表,最终需要其他联接:

F.ex。,当@order_type为1时,它应按ID排序,当它为2时,它应该以价格表和订单顺序将ID加入到匹配价格中。

目前我有3个不同的@order_type,但未来可能会有所增加。 我希望尽快将结果返回给我的应用程序(当然),它可能会产生最多约50K varchar(50)个键。

有没有优雅的方法可以实现这一点而无需多次编写查询? 我想避免这样的事情:

IF @count_only = 1 BEGIN
    SELECT COUNT(1) FROM (mycomplexquery)
ELSE IF @order_type = 1 BEGIN
    SELECT [id] FROM (mycomplexquery) ORDER BY [id]
ELSE IF @order_type = 2 BEGIN
    SELECT [id] FROM (mycomplexquery)
    JOIN (prices) ON (...) ORDER BY [price]
END

我可以创建一个表变量来存储来自(mycomplexquery)的结果,但我担心它可能会减慢查询速度以创建额外的表,所以我想我会问是否有人有一个聪明的主意。

1 个答案:

答案 0 :(得分:0)

If you want to avoid messy code (like if/else structures within a query) in your SP, your best bet is to create two SPs. One for the count only - and one for the list of IDs. Or you could break them into totally separate queries and keep them in the same SP. Having a CASE statement in your order by clause is no big deal for your second variable:

IF @count_only = 1
    BEGIN
        SELECT COUNT(*) FROM (mycomplexquery)
    END
ELSE
    BEGIN
        SELECT DISTINCT([id]) FROM (mycomplexquery)
        JOIN (prices) 
            ON (...) 
        ORDER BY 
            CASE WHEN @order_type = 1
                THEN [id]
                ELSE [price]
            END

    END