SQL通过循环重置变量值

时间:2015-07-21 09:11:15

标签: sql sql-server tsql

我有以下查询:

Declare @variable int
Set @variable = 10
select @variable = case
                        when max(max_val) >= @variable then @variable
                        else max(max_val)
                    end
from dsa_finaldataset
where account_id = 'a1'
and product_id = 'p1'
and product = 'x1'

select * from
(select *, row_number () over (partition by account_id, product_id,product order by revenue desc) as rk from
(select * from test_data
where account_id = 'a1'
and product_id = 'p1'
and product = 'x1'
and @variable between min_val and max_val)x)y
where y.rk =1;

这里我声明一个值设置为它的变量,并基于其中一个列值(max_val)我要么保留声明的值,要么将max_val列的值赋给变量。符合条件的记录将是查询输出。我对此提出的问题:

我有大约5种不同的产品,每种产品都有不同的min_val和max_val。但是,输入的变量将是相同的,并且在每个产品的情况下保持相同的条件。无论如何我可以使用循环结构,我可以在同一个查询中获得所有5个产品x1,x2,x3,x4和x5的输出,这样在评估变量条件和查询执行时,变量被重新分配其原始值,之后将检查条件并再次查询下一个产品?

1 个答案:

答案 0 :(得分:0)

根据我的理解,您可以将上述代码包含在一个函数中,其中product是一个参数(或者可能是all-account_id,product_id和product),并在此函数上使用APPLY运算符来获取所有数据你的产品:

CREATE FUNCTION dbo.fn_doCalculations (@account_id VARCHAR(10), @product_id VARCHAR(10), @product VARCHAR(10))
RETURNS @return TABLE (
        /* declare columns needed here */ 
    )
AS 
BEGIN
    Declare @variable int
    Set @variable = 10
    select @variable = case
                            when max(max_val) >= @variable then @variable
                            else max(max_val)
                        end
    from dsa_finaldataset
    where account_id = @account_id
    and product_id = @product_id
    and product = @product

    INSERT INTO @return (/* declared columns here */)
    select * 
    from 
    (   select *, row_number () over (partition by account_id, product_id,product order by revenue desc) as rk 
        from    (   select * 
                    from test_data
                    where account_id = @account_id
                        and product_id = @product_id
                        and product = @product
                        and @variable between min_val and max_val) x
                ) y
    where y.rk =1;

    RETURN
END

创建该功能后,您可以像这样查询以获得所有产品(或者只是您需要的产品)的结果:

SELECT *
FROM    dbo.your_products_table P
        OUTER APPLY dbo.fn_doCalculations(P.account_id, P.product_id, P.product)
WHERE   P.product_id IN ('x1', 'x2', 'x3', 'x4', 'x5')

这会将您的代码(功能)应用于您需要的产品。