如何替换SQL更新查询中的定界列值?

时间:2018-07-20 19:59:07

标签: sql sql-server

“列”中的值采用Name_city_age_ID格式(下划线分隔)。 年龄总是一片空白。其他值可能为空白。因此,列中的值就像:

John_London__1223,
Mary_Paris__,
Dave____,
Smith____1012,
___2334

现在我所有行的年龄都为22岁,并且我想替换列中的所有值,因此新列应为:

John_London_22_1223,
Mary_Paris_22_,
Dave__22_,
Smith__22_1012,
__22_2334,

如何为此编写更新查询?

2 个答案:

答案 0 :(得分:1)

使用STUFF,但您实际上应该规范化数据。这将寻找_的第二个实例,并添加22

declare @table table(col varchar(64))
insert into @table
values
('John_London__1223'),
('Mary_Paris__'),
('Dave____'),
('Smith____1012'),
('___2334')

select * from @table

--update the column 

update @table
set col = stuff(col,charindex('_',col) + charindex('_',right(col,len(col) - charindex('_',col))) + 1,0,'22')


--see the results

select * from @table

答案 1 :(得分:1)

调用CHARINDEX函数两次即可。以下是用于检查结果的SELECT查询,转换为UPDATE:

SELECT
  str,
  STUFF(str, CHARINDEX('_', str, CHARINDEX('_', str) + 1) + 1, 0, '22') AS newstr
FROM testdata

SQL Fiddle

相关问题