2017-04-20 44 views
0

我有一個更改表,我需要分配id的交易表中的下一個可用id。批次完成後,它將被髮布到交易表。我如何在select insert語句中獲得另一個表的max + 1?我必須將它連接到同一查詢中的code_id。插入選擇更改表與其他表的交易最大id

INSERT INTO CHANGES 
(P.CODE, P.ID, P.CODE_ID, P.FIRST_NAME, P.MIDDLE_NAME, P.LAST_NAME) 
SELECT 'P', MAX(transactionstable.ID) +1, 
'P0000' + MAX(transactionstable.ID) +1, 'first','middle','last'; 
+4

爲什麼不使用'identity'列呢? – Igor

+0

'SELECT'P',(SELECT max(id)+ 1 FROM transactiontable),'P0000'+(SELECT max(id)+ 1 FROM transactiontable),'first',...' – JNevill

+0

爲什麼需要生成更改表中的ID。爲什麼不讓交易表中的標識列滿足要求。如果在事務表中發生任何其他插入,則在更改表中創建一個ID時,您始終有風險,該更改表與事務表中的ID重複。 –

回答

0
INSERT INTO CHANGES (
         P.CODE, 
         P.ID, 
         P.CODE_ID, 
         P.FIRST_NAME, 
         P.MIDDLE_NAME, 
         P.LAST_NAME 
         ) 
    SELECT P,  --remove single quote, otherwise it is static value 
      MAX(transactionstable.ID) +1, 
      'P0000' + CAST((MAX(transactionstable.ID) +1) as VARCHAR(50)), --Conversion here for string concatenation 
      first, --remove single quote, otherwise it is static value 
      middle, --remove single quote, otherwise it is static value 
      last --remove single quote, otherwise it is static value 

/********************* 
    missing here 
**********************/  
    FROM transactions