首页 > 解决方案 > 使用三列的串联创建 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

我该怎么做呢?

标签: sqlconcatenation

解决方案


假设您使用的是 SQL Server,您只需执行以下操作:

Productcode as (concat(GroupId, '-', SubGroupId, '-', ProductId)),

您的代码的问题在于它+被解释为加法,而不是字符串连接。

在更新的版本中,您可以使用concat_ws()

Productcode as (concat_ws('-', GroupId, SubGroupId, ProductId)),

CONCAT_WS允许您指定一个分隔符,以便在要连接的实例之间注入。

另请注意,当您使用or时,输入会隐式转换为char类型,因此此语法比其他内联值连接方法更简单。CONCATCONCAT_WS


推荐阅读