SQL Server get Identity Number and assign to another column value(SQL Server 获取标识号并分配给另一个列值)
问题描述
我是 SQL Server 初学者,需要满足要求但不知道如何
I am a beginner SQL Server student and need to fulfill a requirement and don't know how
对于表 Products 我有列 ProductID、ProductName、SerialNo.
For table Products I have columns ProductID, ProductName, SerialNo.
SerialNo 应该从 1001 开始并加 1,同时 ProductId 应该从 P1001, P1002<开始/code> 等等...
The SerialNo should start from 1001 and increment by 1 and at the same time ProductId should start as P1001, P1002 and so...
我定义了
SerialNo INT Identity(1001, 1)
并且不知道如何获取标识值并将其附加到P"并尝试使用变量但无法弄清楚
and don't know how to take the identity value and append it to 'P' and tried using variables and can't figure it out
BEGIN
DECLARE @ProductID VARCHAR(5)
SET @ProductID = 'P' + CAST(@@IDENTITY AS VARCHAR)
INSERT INTO Product VALUES(@ProductID,'Nokia')
SELECT * FROM Product
END
我得到了
ProductID Name SerialNo
--------------------------------------
NULL NOKIA 1001
预期输出是
ProductID Name SerialNo
-------------------------------------
P1001 NOKIA 1001
推荐答案
@@IDENTITY 保留会话中最后一个插入标识,所以它对你没有用,你有几个选择:
@@IDENTITY keeps the last insert identity in the session, so its not useful for you , you have several option:
添加计算列:
add a computed column :
alter table product add ProductId as concat('P',SerialNo)
使用 IDENT_CURRENT :IDENT_CURRENT 为您提供表中的最后一个标识值
use IDENT_CURRENT : IDENT_CURRENT give you the last identity values in the table
INSERT INTO Product VALUES(concat('P',IDENT_CURRENT('dbo.product')+1) ,'Nokia')
SELECT * FROM Product
我建议你使用计算列,但是你总是可以重现 productId ,不知道为什么你需要保存它,它是冗余的
I recommend you go with computed column , however you always can reproduce the productId , not sure why you need to save it , its redundunt
这篇关于SQL Server 获取标识号并分配给另一个列值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:SQL Server 获取标识号并分配给另一个列值
基础教程推荐
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- 在 SQL 中连接多个表 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- 无法解决整理冲突 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- 是否可以执行按位分组功能? 2021-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
