Transact SQL Subquery调用函数不正确的语法

时间:2015-04-17 16:14:19

标签: sql sql-server tsql syntax-error

我在'附近的语法不正确。'并且似乎无法在以下代码中找出原因:

select 
o.object_id,
(select top 1 Zone from dbo.getzone(o.object_id)) as Zone from object as o

getzone是一个表值函数,当我直接引用它时,或者如果我放入一个特定的object_id,但是每当我尝试使它成为动态时,我都会得到语法错误。

我错过了什么?

3 个答案:

答案 0 :(得分:1)

修复别名

select  o.object_id, 
        (select top 1 Zone from dbo.getzone(o.object_id)) as Zone 
from object AS o

答案 1 :(得分:1)

你做不到。您需要一个只返回一个结果的标量版本。如果你愿意,它可以只是一个包装脚本。像这样:

CREATE FUNCTION [dbo].[getSingleZone](@object_id varchar(20))
RETURNS varchar(20)
AS
BEGIN
DECLARE @Zone varchar(20)
select @Zone = max(Zone) from dbo.getzone(@object_id)
return @Zone 
END

select 
o.object_id,
dbo.getSingleZone(o.object_id) as Zone from object o

我不知道你的数据类型,所以我猜对了。

答案 2 :(得分:1)

也许我错过了这个问题,但这似乎有效。使用内置函数的名称(OBJECT_ID)作为列名可能没有帮助。

SQL fiddle示例或代码如下。

-- TVF without parameter.
create function dbo.GetZone()
  returns table as
  return
    select Id, Letter
      from
      ( values ( 1, 'Aleph' ), ( 2, 'Beth' ), ( 3, 'Gimmel' ) ) as Letters( Id, Letter );
go

-- TVF with parameter;
create function dbo.GetZone2( @Id as Int )
  returns table as
  return
    select Id, Letter
      from dbo.GetZone() where Id = @Id;
go

select * from dbo.GetZone();
select * from dbo.GetZone2( 2 );

-- Sample table and data.
declare @Objects as table ( Id Int Identity, Letter VarChar(16) );
insert into @Objects values ( 'Alpha' ), ( 'Beta' ), ( 'Gamma' );
select * from @Objects;

-- Correlated subquery.
select O.Id, O.Letter as [Greek],
  ( select top 1 Letter from dbo.GetZone( ) where Id = O.Id ) as [Hebrew]
  from @Objects as O;
select O.Id, O.Letter as [Greek],
  ( select top 1 Letter from dbo.GetZone2( O.Id ) ) as [Hebrew]
  from @Objects as O;

-- Houseclean.
drop function dbo.GetZone;
drop function dbo.GetZone2;