2011-07-22 40 views
1

我想在小設置表中插入一條新記錄,並且想要獲取DisplayOrder字段的MAX值並將其添加10。插入值的MAX函數出現錯誤。爲INSERT語句獲取字段的最大值

INSERT INTO tMrMenu 
     ([ParentId] 
     ,[DisplayOrder] 
     ,[ItemName] 
     ,[ItemDescription] 
     ,[ItemURL] 
     ,[ItemImage] 
     ,[CreateDate] 
     ,[CreateUser] 
     ,[LastUpdateDate] 
     ,[LastUpdateUser] 
     ,[module] 
     ,[isactive]) 
SELECT 
     (1 
     , (SELECT MAX(DisplayOrder) + 10 FROM tMrMenu) 
     , 'EDM Summary Text' 
     , 'EDM Summary Text' 
     , '/Offline/Reports/EdmSummaryText' 
     , 'cli.gif' 
     , GETDATE() 
     , 'Garry.Bargsley' 
     , GETDATE() 
     , 'Garry.Bargsley' 
     , 'MR' 
     , 1) 
+1

Whar 「錯誤」,你得到什麼? –

+0

你很希望知道這個「技巧」在負載很重的情況下非常容易重複......如果多個客戶端同時讀取當前的MAX(DisplayOrder),並且每個客戶端都增加10個,同樣的,可能會出現新的價值。 –

回答

1

你有多餘的括號:

INSERT INTO tMrMenu 
     ([ParentId] 
     ,[DisplayOrder] 
     ,[ItemName] 
     ,[ItemDescription] 
     ,[ItemURL] 
     ,[ItemImage] 
     ,[CreateDate] 
     ,[CreateUser] 
     ,[LastUpdateDate] 
     ,[LastUpdateUser] 
     ,[module] 
     ,[isactive]) 
SELECT 
     1 
     , (SELECT MAX(DisplayOrder) + 10 FROM tMrMenu) 
     , 'EDM Summary Text' 
     , 'EDM Summary Text' 
     , '/Offline/Reports/EdmSummaryText' 
     , 'cli.gif' 
     , GETDATE() 
     , 'Garry.Bargsley' 
     , GETDATE() 
     , 'Garry.Bargsley' 
     , 'MR' 
     , 1 
0
Declare @max int 
SET @max = (SELECT MAX...) 

INSERT INTO tMrMenu... 
SELECT 
... 
@max, 
... 
0
INSERT INTO tMrMenu 
     ([ParentId] 
     ,[DisplayOrder] 
     ,[ItemName] 
     ,[ItemDescription] 
     ,[ItemURL] 
     ,[ItemImage] 
     ,[CreateDate] 
     ,[CreateUser] 
     ,[LastUpdateDate] 
     ,[LastUpdateUser] 
     ,[module] 
     ,[isactive]) 
SELECT MAX(DisplayOrder) + 10 
     , 'EDM Summary Text' 
     , 'EDM Summary Text' 
     , '/Offline/Reports/EdmSummaryText' 
     , 'cli.gif' 
     , GETDATE() 
     , 'Garry.Bargsley' 
     , GETDATE() 
     , 'Garry.Bargsley' 
     , 'MR' 
     , 1 
FROM tMrMenu