sybase ISNULL - 条件太长了?

时间:2012-09-18 22:32:39

标签: sql sybase

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

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

的括号太多了

1 个答案:

答案 0 :(得分: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