Sql 服务器函数 return 中的多个 If else 错误

Multiple If else in Sql Server Function return error

我正在尝试获取一个唯一的 ID 号,我已经编写了以下 SQL 服务器函数来完成它。我会给该函数提供当前管理员的 ID,它将位于左侧的第一个数字上。现在我只想 return 一个非常独特的数字。我使用了多个 if ,所以不应该匹配。我希望在 table orderdetailstb 中没有 orderid 时。如果有的话应该+1.

USE [ResturantManagementSystem]
GO
/****** Object:  UserDefinedFunction [dbo].[we]    Script Date: 11/11/2016 11:48:59 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create FUNCTION [dbo].[UniqueOrderId] (@currentAdminid int)
RETURNS int
AS BEGIN
declare @UniqueOrderId int
if (select orderid from OrderDetailsTB) is null
return (select concat(left(@currentAdminid,1),CONVERT(int,getdate(),112),right('1',1)) from Admin)
else
if
(select max(CONVERT(int,getdate(),112)) from OrderDetailsTB)>CONVERT(int,getdate(),112)
return (select concat(left(@currentAdminid,1),CONVERT(int,getdate(),112),right('1',1)) from Admin)
else
return (select concat(left(@currentAdminid,1),CONVERT(int,getdate(),112),right(select max(orderid)+1 from OrderDetailsTB),3) from Admin)
return @UniqueOrderId
END

问题是它在

处给出错误
return (select concat(left(@currentAdminid,1),CONVERT(int,getdate(),112),right(select max(orderid)+1 from OrderDetailsTB),3) from Admin)

错误是

Msg 156, Level 15, State 1, Procedure UniqueOrderId, Line 12 Incorrect syntax near the keyword 'select'. Msg 102, Level 15, State 1, Procedure UniqueOrderId, Line 12 Incorrect syntax near ')'.

我该怎么做,是否适合我使用某个函数,或者我应该将其移至存储过程。

你能试试这个吗:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create FUNCTION [dbo].[UniqueOrderId] (@currentAdminid int)
RETURNS int
AS BEGIN
declare @UniqueOrderId int
if (select orderid from OrderDetailsTB) is null
return (select concat(left(@currentAdminid,1),CONVERT(int,getdate(),112),right('1',1)) from Admin)
else
if
(select max(CONVERT(int,getdate(),112)) from OrderDetailsTB)>CONVERT(int,getdate(),112)
return (select concat(left(@currentAdminid,1),CONVERT(int,getdate(),112),right('1',1)) from Admin)
else
return (select concat(left(@currentAdminid,1),CONVERT(int,getdate(),112)
       ,right(maxOrderId,3)) 
        from Admin
        cross apply (select max(orderid)+1 from OrderDetailsTB) ds(maxOrderId)

        )
return @UniqueOrderId
END

想法是使用 outercross apply 以转换内联 select 语句:

return (select concat(left(@currentAdminid,1),CONVERT(int,getdate(),112),right(select max(orderid)+1 from OrderDetailsTB),3) from Admin) 

至:

return (select concat(left(@currentAdminid,1),CONVERT(int,getdate(),112)
       ,right(maxOrderId,3)) 
        from Admin
        cross apply (select max(orderid)+1 from OrderDetailsTB) ds(maxOrderId)

        )