我希望使用SQL服务器从客户端的全名中获得带有首字母的名称。格式应该是除了姓+姓以外的名字和中间名的第一个字母
如果全名是John Cena,那么输出应该是J Cena
如果全名是Wathsala Malshani Perera,那么输出应该是W。
请帮助我建立一个查询。谢谢
发布于 2022-11-18 11:31:25
SELECT LEFT(FirstName, 1), LastName FROM Table左(列,1)将只返回列的第一个字母。如果你有一个中间的名字,应该是这样的
SELECT LEFT(FirstName, 1), LEFT(MiddleName, 1), LastName FROM Table您还可以使用SUBSTRING(FirstName,1,1),这相当于我所展示的左的用法。
发布于 2022-11-18 12:25:54
你好,我正在检查您的请求,我认为最好的方法应该是您使用存储过程,我不会在这个答案中讨论这个主题,但是我在存储过程中留下了一个示例算法。
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诚挚的问候
https://stackoverflow.com/questions/74488889
复制相似问题