改善T-sql代码的运行时间

时间:2016-02-10 21:46:47

标签: sql-server tsql

我想用T-sql代码改善运行时间。

插入查询需要很长时间。有没有机会使用不同的方法? 这是我的代码

Create PROCEDURE [dbo].[CreateTableDemog] 
 @Age int,
 @RetiredAge int 
as
begin


declare @t as int=1;
declare @tlast as int=@RetiredAge -@Age 
declare @Period as int=0;
BEGIN
    while @t<=@tlast
    begin

        while @Period <=@t-1
        begin

        INSERT INTO dbo.Table (t, Age,Period,Prob)
                    VALUES (@t,@Age+@t,@Period,1);


        set @Period=@Period+1  
        end     
        set @Period=0               
        set @t=@t+1 
    end
end 

1 个答案:

答案 0 :(得分:3)

以下是使用计数表而不是嵌套while循环的方法。这是一个奇怪的要求,但很容易遵循。

Jeff Moden撰写的这篇文章很好地解释了一个标记是什么以及如何使用它。 http://www.sqlservercentral.com/articles/T-SQL/62867/

Create PROCEDURE [dbo].[CreateTableDemog] 
(
    @Age int
    , @RetiredAge int
) as

    set nocount on;

    WITH
        E1(N) AS (select 1 from (values (1),(1),(1),(1),(1),(1),(1),(1),(1),(1))dt(n)),
        E2(N) AS (SELECT 1 FROM E1 a, E1 b), --10E+2 or 100 rows
        E4(N) AS (SELECT 1 FROM E2 a, E2 b), --10E+4 or 10,000 rows max
        cteTally(N) AS 
        (
            SELECT  ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E4
        )

    INSERT INTO dbo.Table
    (
        t
        , Age
        , Period
        , Prob
    )
     select t1.N as T
        , @Age + t1.N as AgePlusT
        , abs(t2.N - t1.N) as Period
        , 1
     from cteTally t1
     join cteTally t2 on t2.N <= t1.N
     where t1.N <= @RetiredAge - @Age
     order by t1.N
        , @Age + t1.N
        , abs(t2.N - t1.N);

GO