我创建了以下
CREATE FUNCTION
声明:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION dbo.GelLastName
(
-- Add the parameters for the function here
@FullName NCHAR(100)
)
RETURNS NCHAR(100)
AS
BEGIN
-- Declare the return variable here
DECLARE @LastName NCHAR(100)
DECLARE @CommaPosition INTEGER
-- Add the T-SQL statements to compute the return value here
SET @CommaPosition = PATINDEX('%,%',@FullName)
CASE @CommaPosition
WHEN 0 THEN
SET @LastName = TRIM(UPPER(LEFT(@FullName,1))+LOWER(RIGHT(@FullName,LEN(@FullName)-1)))
ELSE
SET @LastName = TRIM(UPPER(LEFT(LEFT(@FullName,@CommaPosition-1),1))+LOWER(RIGHT(LEFT(@FullName,@CommaPosition-1),LEN(LEFT(@FullName,@CommaPosition-1))-1)))
END
-- Return the result of the function
RETURN @LastName
END
GO
尝试运行该语句时出现几个错误(实际上第一个错误甚至在语句运行之前):
我不确定我做错了什么,但我确信我犯了一些语法错误。
我使用了 SQL 2022 的语法(!!!) 有一个函数 string_Split 可以在逗号上分割字符串
提供了 2 个仅包含姓氏的字符串和包含first、last 组合的字符串示例 这是我的理解和您的要求
CREATE or ALTER FUNCTION dbo.GelLastName
(
-- Add the parameters for the function here
@FullName NCHAR(100)
)
RETURNS NCHAR(100)
AS
BEGIN
-- Declare the return variable here
DECLARE @LastName NCHAR(100)
DECLARE @CommaPosition INTEGER
-- Add the T-SQL statements to compute the return value here
SET @CommaPosition = PATINDEX('%,%',@FullName)
SELECT TOP (1) @LastName = val
FROM (
SELECT
rn = ROW_NUMBER() OVER (ORDER BY (SELECT NULL)),
val = RTrim(LTRIM(value))
from string_split(@FullName, ',')
) c order by c.rn desc
RETURN Upper(substring(@LastName, 1,1)) + Lower(Substring(@lastName, 2, Len(@lastName)))
END
GO
select dbo.GelLastName('indigo, Montoya')
select dbo.GelLastName('montoya')