SQL查询用于分隔的字符串

huangapple go评论96阅读模式
英文:

SQL query for delimited string

问题

我有一个表格中的字符串列,它的长度可能不同,并以 / 分隔,如下例所示。我尝试删除最后一个 / 标志之后的任何字符,包括最后一个 / 标志。任何想法将不胜感激,我已经尝试了 left、charindex 等选项,但没有成功。

删除的原因是为了能够与其他表格进行连接以查找值。

Source:
Sh/cm/rq;
Sh/nj/mdr/wep;
Sh/kl/uhj/tyu bh/red

期望的输出:
Sh/cm;
Sh/nj/mdr;
Sh/kl/uhj/tyu bh

我已经尝试了 left、charindex 等选项,但没有成功。

Source:
Sh/cm/rq;
Sh/nj/mdr/wep;
Sh/kl/uhj/tyu bh/red

期望的输出:
Sh/cm;
Sh/nj/mdr;
Sh/kl/uhj/tyu bh

英文:

I have string column in a table, its length can be different and delimited by /, examples below. I am trying to remove any last characters after last / sign, including last / sign. Any ideas would be appreciated, I haves tried left, charindex, etc options but no luck.
Reason to remove is so that I can do join with other table to find values.

  1. Source:
  2. Sh/cm/rq;
  3. Sh/nj/mdr/wep;
  4. Sh/kl/uhj/tyu bh/red
  5. Looking to output
  6. Sh/cm;
  7. Sh/nj/mdr;
  8. Sh/kl/uhj/tyu bh

I haves tried left, charindex, etc options but no luck.

  1. Source:
  2. Sh/cm/rq;
  3. Sh/nj/mdr/wep;
  4. Sh/kl/uhj/tyu bh/red
  5. Looking to output
  6. Sh/cm;
  7. Sh/nj/mdr;
  8. Sh/kl/uhj/tyu bh

答案1

得分: 0

以下是代码的中文翻译:

  1. 创建表格 test(id int,keys varchar(100));
  2. test 插入值
  3. (1,'Sh/cm/rq')
  4. ,(2,'Sh/nj/mdr/wep')
  5. ,(3,'Sh/kl/uhj/tyu bh/red')
  6. ;
  7. 选择 *
  8. , charindex('/',keys)>0 时,
  9. 反转(
  10. 子串(反转(keys),charindex('/',反转(keys))+1,100)
  11. )
  12. 否则 keys
  13. 作为 newkeys
  14. test

请注意,代码中的特殊字符(如''')已被恢复为原始的单引号。

英文:

Try this

  1. create table test(id int,keys varchar(100));
  2. insert into test values
  3. (1,'Sh/cm/rq')
  4. ,(2,'Sh/nj/mdr/wep')
  5. ,(3,'Sh/kl/uhj/tyu bh/red')
  6. ;
  7. select *
  8. ,case when charindex('/',keys)>0 then
  9. reverse(
  10. substring(reverse(keys),charindex('/',reverse(keys))+1,100)
  11. )
  12. else keys
  13. end newkeys
  14. from test

huangapple
  • 本文由 发表于 2023年4月13日 20:55:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76005701.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定