我在表格中有2列:[CatId],[ItemId]
CatId为4位且ItemId为1或2.我想要实现的是将ItemId替换为串联[CatId] + [ItemId],但如果ItemId为1位,则添加0。
例如:
CatId: 1555, ItemId: 12 -> ItemId: 155512
CatId: 1555, ItemId: 2 -> ItemId: 155502
答案 0 :(得分:1)
我会这样做
select cast(catId as int) * 100 + cast(itemid as int)
如果你想把它作为一个字符串:
select cast(cast(catId as int) * 100 + cast(itemid as int) as varchar(255))
答案 1 :(得分:1)
如果您想更新您的表格,请尝试以下选项:
UPDATE yourTable
SET ItemId = CatId + RIGHT('00' + ItemId, 2);
这假定CatId
和ItemId
列是文本而不是数字。如果它们是数字的,那么请看戈登的答案。
答案 2 :(得分:0)
CREATE TABLE [dbo].[Test](
[CatId] [char](4) NULL,
[ItemId] [char](2) NULL
) ON [PRIMARY]
Insert Data
USE [ABC]
GO
INSERT INTO [dbo].[Test]([CatId] ,[ItemId]) VALUES ('1231','1')
INSERT INTO [dbo].[Test]([CatId] ,[ItemId]) VALUES ('1232','2')
INSERT INTO [dbo].[Test]([CatId] ,[ItemId]) VALUES ('1233','10')
INSERT INTO [dbo].[Test]([CatId] ,[ItemId]) VALUES ('1234','23')
INSERT INTO [dbo].[Test]([CatId] ,[ItemId]) VALUES ('1237','6')
Select [CatId]+ (Case WHEN len(ItemId) =1 THEN '0'+[ItemId] ELSE [ItemId] END ) as DATA from [dbo].[Test]
**Result**
DATA
123101
123202
123310
123423
123706