[英]Multiple If else in Sql Server Function return error
我正在嘗試獲取唯一的ID號,並且我編寫了以下SQL Server函數來實現。 我將給該函數當前管理員的ID,該ID將在左側的第一位。 現在我希望它只返回一個非常唯一的數字。 我使用了多個if,以便不存在匹配項。 我希望在表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)
錯誤是
消息156,級別15,狀態1,過程UniqueOrderId,第12行關鍵字“ select”附近的語法錯誤。 消息102,級別15,狀態1,過程UniqueOrderId,第12行')'附近的語法不正確。
我該怎么辦?如果適合使用某個函數,還是應該將其移向存儲過程?
您可以嘗試一下:
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
這個想法是使用outer
或cross
應用來轉換內聯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)
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.