首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用sql server从全名获取带有初始值的名称。

使用sql server从全名获取带有初始值的名称。
EN

Stack Overflow用户
提问于 2022-11-18 11:19:57
回答 2查看 31关注 0票数 -1

我希望使用SQL服务器从客户端的全名中获得带有首字母的名称。格式应该是除了姓+姓以外的名字和中间名的第一个字母

如果全名是John Cena,那么输出应该是J Cena

如果全名是Wathsala Malshani Perera,那么输出应该是W。

请帮助我建立一个查询。谢谢

EN

回答 2

Stack Overflow用户

发布于 2022-11-18 11:31:25

代码语言:javascript
复制
SELECT LEFT(FirstName, 1), LastName FROM Table

左(列,1)将只返回列的第一个字母。如果你有一个中间的名字,应该是这样的

代码语言:javascript
复制
SELECT LEFT(FirstName, 1), LEFT(MiddleName, 1), LastName FROM Table

您还可以使用SUBSTRING(FirstName,1,1),这相当于我所展示的左的用法。

票数 0
EN

Stack Overflow用户

发布于 2022-11-18 12:25:54

你好,我正在检查您的请求,我认为最好的方法应该是您使用存储过程,我不会在这个答案中讨论这个主题,但是我在存储过程中留下了一个示例算法。

代码语言:javascript
复制
DECLARE @name as nvarchar(50)
DECLARE @nSpace as int
DECLARE @i as int
DECLARE @nameResult as nvarchar(50)
DECLARE @index as int
DECLARE @newname as nvarchar(50)
--you can replace the name for test if all works well
--that variable @name you need to pass in store procedure
SET @name = 'John Cena'
--get the number of the spaces in the string
SET @nSpace = LEN(@name)-LEN(REPLACE(@name, ' ', ''))
--check if the number the spaces is even or odd, if is even need add a space at the end
if @nSpace % 2 = 0 
    SET @name = @name + ' '

--SELECT @nSpace
--index used in the loop
SET @i = 1
--inicialization the variable nameresult
SET @nameResult = ''

while @i <= @nSpace
begin
    --get the index of the position of the space
    SET @index = CHARINDEX(' ',@name)
    --get the first letter of the substring
    SET @newname = SUBSTRING(@name,1,@index)
    --start to mount the name
    SET @nameResult = @nameResult + LEFT(@newname,1) + ' '
    --remove from the name the part already usend
    SET @name = RIGHT(@name,len(@name)-(@index-1))
    --increase the loop
    SET @i = @i + 1

end
--finish with the last name
SET @nameResult = @nameResult + @name
--show the result, in the store procedure that should be the return of the function
SELECT @nameResult

诚挚的问候

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74488889

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档