从SQL Query中设置SET的值

时间:2014-02-03 18:08:38

标签: sql-server

Noob程序员在这里:

我有一个使用SET命令设置变量的函数。我试图遍历表中的所有记录并运行该函数,但我无法弄清楚如何使其工作。不知道如何让查询拉入其查看的当前记录的列,或者我应该如何进行循环,或者如何设置结果。尝试过CROSS APPLY,但我无法让它发挥作用。

if exists(Select Lat, Long From DDD WHERE Ad1 is not Null)
begin
    DECLARE @address nvarchar (100);
    set @address = (Select Ad1 from DDD where ID = id);

    DECLARE @state nvarchar (100);
    SET @state = 'FL';

    DECLARE @zip nvarchar (100);
    SET @zip = (Select AD2 from DDD where ID = id);

    DECLARE @city nvarchar (100);
    SET @city = 'Miami';

    DECLARE @nation nvarchar (2);
    SET @nation = 'us';

    DECLARE @g geography;

    WAITFOR DELAY '00:00:00.050'
    SET @g = dbo.Geocode(@nation, @state, @city, @zip, @address);

    SELECT @g.Long;
    SELECT @g.Lat;
    Update DDD Set Lat = @g.Lat
    Update DDD Set long = @g.Lat
END

[dbo].[DDD](
[id] [int] IDENTITY(1,1) NOT NULL,
[Day] [nvarchar](50) NULL,
[CaseNum] [nvarchar](50) NULL,
[FolioNum] [nvarchar](50) NULL,
[Ad1] [nvarchar](50) NULL,
[AD2] [nvarchar](50) NULL,
[LD] [nvarchar](250) NULL,
[FJ] [nvarchar](150) NULL,
[AV] [nvarchar](50) NULL,
[PMB] [nvarchar](50) NULL,
[BB] [nvarchar](50) NULL,
[LSSQ] [nvarchar](50) NULL,
[LSQ] [nvarchar](50) NULL,
[status] [bit] NULL,
[Notes] [nvarchar](300) NULL,
[WF] [nvarchar](300) NULL,
[Type] [nvarchar](300) NULL,
[Lat] [float] NULL,
[long] [float] NULL,

1 个答案:

答案 0 :(得分:0)

试试这个:

Select @address =  Ad1 from DDD where ID = id;

附录:

我假设函数Geocode返回一个表(带有Lat和Long字段的单个记录)。您可以使用CTE更新DDD表的每一行,如下所述。

DDD中的初始样本数据:

| id | lat | long | Ad |
------------------------     
| 1  | NULL| NULL | A  |
| 2  | NULL| NULL | B  |
| 3  | NULL| NULL | A  |
| 4  | NULL| NULL | C  |

让Geocode函数获取Lat和Long值的基础表具有数据:

| Ad | Lat | Long |
-------------------
|  A | 12  | 45   |
|  B | 13  | 55   |

让地理编码功能定义如下:

create function Geocode(@add varchar)
returns table
as
return (SELECT * from latlongtable where [add] = @add)

使用以下查询可以更新DDD表中的lat long信息:

with cte_d(id1,Ad)
as
(
  select ID as id1, Ad from ddd
)
update d 
set d.lat = (select lat from Geo(d.Ad)), long = (select long from Geo(d.Ad)) 
from ddd d 
where d.id = id 

运行上述查询后,DDD表如下所示:

| id | lat | long | Ad |
------------------------     
| 1  | 12  | 45   | A  |
| 2  | 13  | 55   | B  |
| 3  | 12  | 45   | A  |
| 4  | NULL| NULL | C  |

根据您的需要自定义上述CTE查询,并告诉我您是否能够使其正常工作。