如果我执行此查询,我将获得输出,但不是所需的输出。我想得到输出:
FirstName LastName
ADT NULL
----------------------------------------------------------------------------
这是我的问题:
DECLARE @FullName VARCHAR(100)
SET @FullName = 'ADT'
SELECT SUBSTRING(@FullName, 1, NULLIF(CHARINDEX(' ', @FullName) - 1, -1)) AS [FirstName],
SUBSTRING(@FullName, CHARINDEX(' ', @FullName) + 1, LEN(@FullName)) AS [LastName]
此查询的输出是:
FirstName LastName
NULL ADT
------------------------------------------
提前感谢您的帮助。
答案 0 :(得分:0)
两个选项:
@FullName
包含空格或
通过在末尾添加空格来删除特殊情况。
declare @fullName varchar(100) = 'ADT'
select
LEFT(@fullName, charindex(' ',@fullName+' ')-1) as FirstName,
SUBSTRING(@fullname,charindex(' ',@fullName+' ')+1,LEN(@fullname)) as last
答案 1 :(得分:0)
也许不是最有效但符合要求的。
DECLARE @FullName VARCHAR(100)
SET @FullName = 'ADT'
SELECT SUBSTRING(@FullName, 0, ISNULL(NULLIF(CHARINDEX(' ', @FullName), 0), LEN(@FullName) + 1)) AS [FirstName]
, SUBSTRING(@FullName, NULLIF(CHARINDEX(' ', @FullName) + 1, 1), LEN(@FullName) - CHARINDEX(' ', @FullName) + 1) AS [LastName]
以下是基于澄清要求的更新声明。 REVERSE字符串函数派上用场,LTRIM是由LastName列上的前导空格问题引起的。
DECLARE @FullName VARCHAR(100)
SET @FullName = 'ADT SAMPLE DATABASE CASE'
SELECT SUBSTRING(@FullName, 0, ISNULL(NULLIF(LEN(@FullName) + 1 - CHARINDEX(' ', REVERSE(@FullName)), 0), LEN(@FullName) + 1)) AS [FirstName]
, LTRIM(SUBSTRING(@FullName, NULLIF(LEN(@FullName) - CHARINDEX(' ', REVERSE(@FullName)), LEN(@FullName)) + 1, LEN(@FullName) - (LEN(@FullName) - CHARINDEX(' ', REVERSE(@FullName))))) AS [LastName]
答案 2 :(得分:0)
你的意思是ADT SAMPLE DATABASE AS FirstName和CASE AS LastName