5
CREATE FUNCTION [dbo].[udfGetNextEntityID]
()
RETURNS INT
AS
BEGIN
    ;WITH allIDs AS
    (
    SELECT entity_id FROM Entity 
    UNION SELECT entity_id FROM Reserved_Entity
    )       
  RETURN (SELECT (MAX(entity_id) FROM allIDs )

END
GO

SQL 不是我的强项,但我无法弄清楚我在这里做错了什么。我希望该函数从 2 个表的联合中返回最大的 entity_id。运行脚本会报错:

 Incorrect syntax near the keyword 'RETURN'.

我查看了在函数中使用 CTE 是否有一些限制,但找不到任何相关内容。我该如何纠正?

4

4 回答 4

7
CREATE FUNCTION [dbo].[udfGetNextEntityID]()
RETURNS INT
AS
BEGIN
  DECLARE @result INT;

  WITH allIDs AS
  (
    SELECT entity_id FROM Entity 
    UNION SELECT entity_id FROM Reserved_Entity
  )       
  SELECT @result = MAX(entity_id) FROM allIDs;

  RETURN @result;

END
GO
于 2013-10-01T15:58:29.233 回答
3

虽然你可以做到,但为什么你需要一个 CTE?

  RETURN
  (
    SELECT MAX(entity_id) FROM
    (
      SELECT entity_id FROM dbo.Entity 
      UNION ALL
      SELECT entity_id FROM dbo.Reserved_Entity
    ) AS allIDs
  );

也没有理由使用UNIONUNION ALL因为这几乎总是会引入昂贵的不同排序操作。在创建/引用任何对象时,请始终使用模式前缀。

于 2013-10-01T16:12:45.863 回答
1

你不能从函数中返回你正在做的事情。

错误

使用局部变量并返回相同的值。

 CREATE FUNCTION [dbo].[udfGetNextEntityID]()
    RETURNS INT
    AS
    BEGIN
      DECLARE @MaxEntityId INT;

      WITH allIDs AS
      (
        SELECT entity_id FROM Entity 
        UNION SELECT entity_id FROM Reserved_Entity
      )       
      SELECT @MaxEntityId = MAX(entity_id) FROM allIDs;

      RETURN @MaxEntityId ;

    END
 GO
于 2013-10-01T16:00:36.000 回答
-1
create function tvfFormatstring (@string varchar(100))
returns @fn_table table
(id int identity(1,1),
item int)
as
begin

insert into @fn_table(item)
declare @result int 
set @string = @string+'-'
;with cte (start,number)
as
(

select 1 as start , CHARINDEX('-',@string,1) as number
union all
select number+1 as start , CHARINDEX('-',@string,number+1) as number from cte 
where number <= LEN(@string)

)

select @result = SUBSTRING(@string,start,number-start) from cte ;
return @result;

end



select * from tvfFormatstring ('12321-13542-15634')
于 2016-03-03T10:11:21.303 回答