1

我正在尝试解开一个非常古老的变量。这是在一个字段中输入的全名,可在两个单独的表中找到。在大多数较新的地方,名称位于三个逻辑列中,第一、中间、最后。在这些中,它们都在一起,我试图将其剥离为第一个首字母,姓氏。我在这里找到以下内容并对其进行了修改:

http://dbaspot.com/sqlserver-programming/365656-find-last-word-string.html

 DECLARE @full_name VARCHAR(20)
 DECLARE @fullname VARCHAR(20)
 SELECT @full_name = REVERSE('John A Test')
 SELECT @fullname = REVERSE('Joe Q Public')

 SELECT @final = ISNULL(
                 (right(@full_name,1) + '.  ' + (REVERSE(SUBSTRING(@full_name, 1, 
                                                   CHARINDEX(' ',@full_name) - 1)))), 

                  (right(@fullname,1) + '.  ' + (REVERSE(SUBSTRING(@fullname, 1, 
                                                   CHARINDEX(' ',@fullname) - 1 ))))
                        )

当我将 full_name 留在那里时,它可以正常工作...返回J. Test。当我将其设为空时,默认值应该是
J. Public,但最终却是.. 当我分别测试每条线时,它们会起作用。我也尝试了 COALESCE,结果相同。ISNULL 或 ???? 的括号是否太多?

4

1 回答 1

1

你有问题right(@full_name,1) + '. ',例如:

select null+'.'

给你.

尝试使用case如下更改您的代码:

 DECLARE @full_name VARCHAR(20)
 DECLARE @fullname VARCHAR(20)
 DECLARE @final VARCHAR(20)
 SELECT @full_name = null--REVERSE('John A Test')
 SELECT @fullname = REVERSE('Joe Q Public')

 SELECT @final = case
                    when @full_name is not null
                       then (right(@full_name,1) + '.  ' + (REVERSE(SUBSTRING(@full_name, 1, 
                                                   CHARINDEX(' ',@full_name) - 1))))
                    else (right(@fullname,1) + '.  ' + (REVERSE(SUBSTRING(@fullname, 1, 
                                                   CHARINDEX(' ',@fullname) - 1 ))))
                 end 
select @final         
于 2012-09-19T07:08:17.370 回答