插入新值时,使用相同id的数字插入另一个字段

时间:2014-06-09 02:28:26

标签: mysql sql sql-server

我正在使用sql server 2012 我的桌子像

表:订单

|idOrder| idCustomer | dateTransaction| invoice |
| 1001  | 104        | 2014-06-09     |         |

idOrder使用自动增量,我想询问如何获取刚插入的id命令并与date transaction结合, 我的SP for insertOrder:

BEGIN
INSERT INTO Order
(
 idCustomer,
 transactionDate,
 invoice
)
VALUES
(
 @idCustomer,
 GETDATE(),
 CAST(datepart(year, getdate()) AS VARCHAR(10)) + CAST(datepart(month, getdate()) AS VARCHAR(10)) + CAST(@idCustomer AS VARCHAR(10))
)
END
到目前为止,我得到了

|idOrder| idCustomer | dateTransaction| invoice     |
| 1001  | 104        | 2014-06-09     |  201406104  |

我想要的是

|idOrder| idCustomer | dateTransaction| invoice     |
| 1001  | 104        | 2014-06-09     |  2014061001 | --> 1001 is idOrder

如何在插入新数据时同时将idOrder(自动增量)转入发票字段/或

exec SP插入后exec SP更新如何获取idOrder,因为IdOrder是自动增量所以它没有参数

感谢

完整的代码有效!

BEGIN
INSERT INTO Order
(
 idCustomer,
 transactionDate,
 invoice
)
VALUES
(
 @idCustomer,
 GETDATE(),
 CAST(datepart(year, getdate()) AS VARCHAR(10)) + CAST(datepart(month, getdate()) AS VARCHAR(10)) + CAST(@idCustomer AS VARCHAR(10))
)
END

DECLARE @ID INT SELECT @ID = SCOPE_IDENTITY() 更新TR_Order SET Invoice = CAST(Invoice AS VARCHAR)+ CAST(@ID AS VARCHAR) WHERE IdOrder = @ID

2 个答案:

答案 0 :(得分:0)

首先插入记录并使用

获取插入的ID
SCOPE_IDENTITY()
OR
@@IDENTITY

DECLARE @ID INT
SELECT @ID =  SCOPE_IDENTITY()
UPDATE TABLE_Name
SET Invoice = CAST(Invoice AS VARCHAR) +  CAST(@ID AS VARCHAR)
WHERE IdOrder = @ID

然后再次更新表格,因为在插入记录之前无法获取ID。

答案 1 :(得分:0)

  1. 插入您的记录
  2. 获取ID
  3. 执行对该记录的更新

假设我们有这张桌子

CREATE TABLE my_table (id INT IDENTITY(1,1), col1 VARCHAR(32));

现在这是您的代码


DECLARE @id INT;

 -- here is your insert statement (1)
INSERT INTO my_table (col1) VALUES('000');

-- get the id (2)
SET @id = scope_identity(); 

-- perform update to that record
UPDATE my_table     
SET col1=col1 + CAST(@id AS VARCHAR)
WHERE id=@id;

Demo