SQL Server - 将一段代码放入视图/临时表中

时间:2016-03-25 14:03:13

标签: sql sql-server

对于上面的标题感到抱歉,我不太确定如何说出来,但这里是要点......

我在下面找到了这个查询,它将计算经度和纬度2点之间的里程......

TableAddress   
Address            Long                  Lat
Address 1    52.5600450207834     -0.274050229426521
Address 2    53.5746997938162     -0.62449270669287
Address 3    50.3404675259117     -5.15208822743251

现在基于PRINT结果,我正在尝试创建一个显示这些结果列表的视图。例如,我有一个名为TableAddress的表,其中包含一个地址列表

TableDestination 
Address            Long                  Lat
Destination 1    52.5063420216939   -2.07973524437415
Destination 2    50.9776014579626   -1.35438374178925
Destination 3    53.5493068199536   -0.679623916124968

我有TableDestination,其中包含目的地列表:

 theView
    AddressName           DestinationName          Distance
    Address 1              Destination 1             38 
    Address 2              Destination 1             49
    Address 3              Destination 1             16
  1. 用户将通过参数
  2. 选择AddressDestination
  3. 根据这个结果,我想创建一个视图,使用上面的查询列出每个地址离目的地的距离。
  4. 我不是在哪里开始所以有人可以指出我正确的方向我如何实现这个目标吗?

    非常感谢

    示例结果:

    {{1}}

1 个答案:

答案 0 :(得分:1)

使用表值函数: 下面是一个例子:

CREATE FUNCTION <function_name> (@prameter1,@parameter2)

RETURNS TABLE

AS

  RETURN

    (SELECT fiedd1,
            field2

         FROM <table name>
         where field like @prameter1
         );

然后问一下:

SELECT * FROM <function_name> (@prameter1,@parameter2)

针对具体需求:

CREATE FUNCTION find_location (@sourceLatitude FLOAT,@sourceLongitude FLOAT,@destinationLatitude FLOAT,@destinationLongitude FLOAT)

RETURNS TABLE

AS

  RETURN

    (select SQRT(POWER(69.1 * ( @destinationLatitude - @sourceLatitude),  
2) + POWER(69.1 * ( @sourceLongitude  
- @destinationLongitude )  
* COS(@destinationLatitude / 57.3), 2))   as location
         );


GO

终于:

SELECT * FROM dbo.find_location (53.0150594250908,  -2.24460456782419,52.002933355733400,-0.976678285584733)