如何使用 SQL 查询将值传递给具有 spatial/geography 数据类型的存储过程

How to pass value to stored procedure with spatial/geography data type using SQL query

我是一名学生,在搜索答案 2 小时后,我希望有人可以帮助我。

我创建了一个需要名称、地址和地理位置的存储过程,然后将一个新分支添加到 Branches table。我正在尝试使用新查询传递地理值,但我一直收到语法错误。

存储过程:

create procedure AddBranch
    @Name nvarchar(50),
    @Address nvarchar(100),
    @GeographicLocation geography
as
begin
    SET NOCOUNT ON

    insert into Branches (Name, Address, GeographicLocation)
    values (@Name, @Address, @GeographicLocation)

    select BranchID 
    from Branches 
    where BranchID = SCOPE_IDENTITY()
end

查询:

exec AddBranch 
    @Name = 'Some Name',
    @Address = 'Some Address',
    @GeographicLocation = geography::Point(47.65100, -122.34900, 4326)

错误:

Incorrect syntax near'::'

有没有办法将地理数据传递给存储过程?

像这样将值放在引号中

exec AddBranch 
@Name = 'Some Name',@Address = 'Some Address',
@GeographicLocation = geography::Point('47.65100', '-122.34900', '4326')
go

尽管根据此自定义 Geography 类型期望其值的方式,这可能不起作用,但它会解决语法错误。

除了将参数括在引号中外,您还需要将方法结果分配给局部变量,以便将值作为参数传递给 T-SQL:

DECLARE @geographyPoint geography = geography::Point('47.65100', '-122.34900', '4326');
exec AddBranch 
    @Name = 'Some Name',
    @Address = 'Some Address',
    @GeographicLocation = @geographyPoint;

作为旁注:

create procedure dbo.AddBranch --always specify schema
    @Name nvarchar(50),
    @Address nvarchar(100),
    @GeographicLocation geography
as
begin
    SET NOCOUNT ON
    SET XACT_ABORT ON --should be in every data modification SP

    insert into dbo.Branches (Name, Address, GeographicLocation) --schema!
    output inserted.BranchID --this
    values (@Name, @Address, @GeographicLocation)

    select SCOPE_IDENTITY() BranchID  --or this

   --absolutely no need in another read operation from persistent table
end