我有一列字符串,如下所示。
1991-001
1991-030
1994-003
Run Code Online (Sandbox Code Playgroud)
并希望通过删除占位符 0 来输出这些字符串
1991-1
1991-30
1994-3
Run Code Online (Sandbox Code Playgroud)
我将如何为 SQL Server 中的每一行动态执行此操作?
如果模式不是 4-3,一种选择是使用 PARSENAME() 和 CONCAT()
例子
Declare @YourTable Table ([SomeCol] varchar(50))
Insert Into @YourTable Values
('1991-001')
,('1991-030')
,('1994-003')
Select *
,NewValue = concat(
try_convert(int,parsename(replace(SomeCol,'-','.'),2))
,'-'
,try_convert(int,parsename(replace(SomeCol,'-','.'),1))
)
From @YourTable A
Run Code Online (Sandbox Code Playgroud)
如果模式是 4-3... left()/right()
Select *
,NewValue = concat(
try_convert(int,left(SomeCol,4))
,'-'
,try_convert(int,right(SomeCol,3))
)
From @YourTable A
Run Code Online (Sandbox Code Playgroud)
两人都会回来
SomeCol NewValue
1991-001 1991-1
1991-030 1991-30
1994-003 1994-3
Run Code Online (Sandbox Code Playgroud)
最后一个选项,只是为了好玩……使用几个 replace()
Select *
,NewValue = replace(replace(SomeCol,'-0','-'),'-0','-')
From @YourTable A
Run Code Online (Sandbox Code Playgroud)