2016-11-11 15 views
0

我想獲得一個唯一的ID號,我已經寫了下面的SQL Server函數來做到這一點。我將給該函數提供當前管理員的ID,它將位於左側的第一個數字上。現在我希望它只返回一個非常獨特的數字。我已經使用了多個,所以不應該有一個匹配。我希望在表orderdetailstb中沒有orderid的時候。如果有,它應該+1。多個如果其他在Sql服務器函數返回錯誤

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線的主題詞近不正確 語法'選擇'。 Msg 102,Level 15,State 1, 過程UniqueOrderId,第12行'''附近語法不正確。

我該怎麼做,如果它適合我​​使用的功能,或者我應該把它移向存儲過程。

回答

1

你可以試試這個:

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適用於以改造直列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) 

     ) 
+2

旁註:'(從OrderDetailsTB選擇max(CONVERT(int,getdate(),112))> CONVERT(int,g etdate(),112)'沒有意義。 –

+0

對不起,這是對該問題的評論。 –

+0

那麼我想每天都需要生成一個新的代碼。 –

相關問題