sql - 使用三列的串联创建 custom_id
问题描述
我有一个名为 Products 的表,其中包含以下列:
create table Products
(ProductId int primary key identity(1,1),
GroupId int foreign key references ProductGroup(GroupId),
SubGroupId int foreign key references ProductSubGroup(SubGroupId),
Productcode as (GroupId + SubGroupId + ProductId),
ProductName nvarchar(50) not null unique,
ProductShortForm nvarchar(5) not null unique,
PiecesInCarton int not null,
WeightPerPiece decimal(4,2) not null,
PurchasePricePerCarton decimal(18,2) not null,
SalePricePerCarton_CatC decimal(18,2) not null,
SalePricePerCarton_CatB decimal(18,2) not null,
SalePricePerCarton_CatA decimal(18,2)
)
如果 GroupId = 34, SubGroupId = 22 并且自动生成 ProductId = 12
那么 ProductCode 应该是 34-22-12
我该怎么做呢?
解决方案
假设您使用的是 SQL Server,您只需执行以下操作:
Productcode as (concat(GroupId, '-', SubGroupId, '-', ProductId)),
您的代码的问题在于它+
被解释为加法,而不是字符串连接。
在更新的版本中,您可以使用concat_ws()
:
Productcode as (concat_ws('-', GroupId, SubGroupId, ProductId)),
CONCAT_WS允许您指定一个分隔符,以便在要连接的实例之间注入。
另请注意,当您使用or时,输入会隐式转换为char类型,因此此语法比其他内联值连接方法更简单。
CONCAT
CONCAT_WS
推荐阅读
- postgresql - Postgresql 在下一个使用第一行值
- c# - 如何使 FileHelpers 忽略定义列之后的列?(即忽略最后的列)
- matlab - 以与 Ginput 相同的方式从 Ginputc 获取子图号(以更快的 Ginput 回答)
- spring - Springboot 2.4.4 和 awsPramstore
- python - Python 中的 ipaddress 模块如何处理 IP
- python - 如何制作一个 python 程序,该程序生成的命令在循环中打印一个从 0000 到 9999 的数字,前面有 4 个字母
- html -
- javascript - React:用嵌套数组映射对象数组
- arrays - 从 X 给定数字中找到总和等于或小于给定数字的所有 5 组
- python - 如何在 Great Exceptions(数据验证工具)中生成新的错误报告或访问最后一个?