T-SQL查询问题?

时间:2010-12-10 17:54:36

标签: tsql

如果我执行此查询,我将获得输出,但不是所需的输出。我想得到输出:

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
------------------------------------------

提前感谢您的帮助。

3 个答案:

答案 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