如何使用T-sql内置函数获取子串 [英] How to get substring with T-sql built-in function

查看:18
本文介绍了如何使用T-sql内置函数获取子串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在 Mytable 列名称中存储了一个类似于firstname lastname"的字符串.然后我想在 SQL 中吸引名字和姓氏,比如

Suppose I have a string like "firstname lastname" stored in Mytable column Name. then I want to attract firstname and lastname in SQL like

select FirstName = substring(Name, ..),  LastName=substring(Name, ...) from Mytable

如何解决这个问题?

推荐答案

您可以使用 charindex 来查找空间的位置:

You could use charindex to find the location of the space:

select FirstName = substring(Name, 1, charindex(' ', Name)),
       LastName = substring(Name, charindex(' ', Name) + 1, len(Name))
from MyTable

这里充斥着各种假设,例如只有一个空格(如果我的名字是比利鲍勃哈里斯或麦当娜呢?)

This is littered with assumptions, e.g. there's exactly one space (what if my name is Billy Bob Harris, or Madonna?)

与其按照您要求的方式进行操作,不如使用 PARSENAME(正如另一条评论所说!).

Rather than do it the way you're asking though, you might be better off using PARSENAME (as another comment says!).

这篇关于如何使用T-sql内置函数获取子串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆