sql-server - How can I remove extra placeholders in this string in SQL?
问题描述
I have a column of strings that look like the following.
1991-001
1991-030
1994-003
and want to output these strings by removing the placeholder 0's to this
1991-1
1991-30
1994-3
How would I go about doing this dynamically for each row in 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
如果模式是 4-3... left()/right()
Select *
,NewValue = concat(
try_convert(int,left(SomeCol,4))
,'-'
,try_convert(int,right(SomeCol,3))
)
From @YourTable A
两者都会返回
SomeCol NewValue
1991-001 1991-1
1991-030 1991-30
1994-003 1994-3
最后一个选项,只是为了好玩......使用几个 replace()
Select *
,NewValue = replace(replace(SomeCol,'-0','-'),'-0','-')
From @YourTable A
推荐阅读
- html - 如何停止背景图像的滚动效果
- node.js - 对齐高图甜甜圈中的标签
- c# - Asp.Net Tag Helper type="date" 允许年份超过 4 位
- c# - 在其他项目 dll 中读取 Service Fabric 项目配置
- django - 如何验证登录
- javascript - React Error : 已声明但它的值从未被读取。[6133]
- highcharts - 如何在高角图表包装器中使用添加系列和更新方法?
- python - 我如何访问kivy中的全局变量
- chart.js - Chartjs条形图试图从数据集中获取标签
- javascript - 在Javascript引擎(v8)中,优化阶段的“隐式调用”到底是什么意思?