使用函数计算2个拉链之间的距离

时间:2015-09-02 14:54:26

标签: sql-server

我有一张前三行的表格:

ship_to_zip Knoxville_Zip   Phoenix_Zip
52773       37909           85009
46341       37909           85009
83114       37909           85009

我有一个函数可以计算2个拉链之间的距离:dbo.ufnzipcodedist_2012(zip1,zip2)

现在我想在我的表格中添加2个列:Miles_from_KnoxvilleMiles_from_Phoenix,每个列分别计算ship_to_id和Knoxville_Zip / Phoenix_Zip之间的里程数。

我试过以下:

select IDENTITY(Int,1,1) ID,*,CAST(0 as float) dist1,CAST(0 as FLOAT) DIST2
INTO #TEMP
from #zip

declare @COUNT INT
DECLARE @DIST1 FLOAT
DECLARE @DIST2 FLOAT

set @COUNT=1

while (@COUNT<=2)
begin
    SELECT @DIST1=dbo.ufnzipcodedist_2012(SHIP_TO_ZIP,KNOXVILLE_ZIP)
            ,@DIST2=dbo.ufnzipcodedist_2012(SHIP_TO_ZIP,PHOENIX_ZIP)
    FROM #TEMP

    UPDATE t SET T.DIST1=@DIST1,t.DIST2=@DIST2
    FROM #TEMP t
    WHERE ID=@COUNT

set @COUNT=@COUNT+1
end

它进入无限循环,列DIST1,DIST2填充0。我哪里做错了?

1 个答案:

答案 0 :(得分:1)

请修改您的查询,如下所示:

        SELECT IDENTITY(INT, 1, 1) ID
            ,*
            ,CAST(0 AS FLOAT) dist1
            ,CAST(0 AS FLOAT) DIST2
        INTO #TEMP
        FROM #zip

        DECLARE @COUNT INT
        ,@DIST1 FLOAT
        ,@DIST2 FLOAT
        ,@MAXID INT

        SET @COUNT = 1

        SELECT @MAXID = MAX(ID)
        FROM #TEMP

        WHILE (@COUNT <= @MAXID)
        BEGIN
            SELECT @DIST1 = dbo.ufnzipcodedist_2012(z1, z2)
                ,@DIST2 = dbo.ufnzipcodedist_2012(z2, z3)
            FROM #TEMP
            WHERE ID = @COUNT

            UPDATE t
            SET T.DIST1 = @DIST1
                ,t.DIST2 = @DIST2
            FROM #TEMP t
            WHERE ID = @COUNT

            SET @COUNT = @COUNT + 1
        END

        SELECT *
        FROM #TEMP

以下是SQL小提琴的链接:http://sqlfiddle.com/#!6/b5699/3