Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/opengl/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在SQL更新查询中替换分隔列值?_Sql_Sql Server - Fatal编程技术网

如何在SQL更新查询中替换分隔列值?

如何在SQL更新查询中替换分隔列值?,sql,sql-server,Sql,Sql Server,列中的值的格式为Name\u city\u age\u 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

列中的值的格式为
Name\u city\u age\u 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,

如何为此编写更新查询?

使用
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

调用两次CHARINDEX
函数就可以了。以下是查看结果的选择查询,转换为更新:

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

这是什么类型的数据库?行是否用逗号分隔?有些行中有什么四个下划线?不要使用分隔列!