Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2012 Forums
 Transact-SQL (2012)
 Best way to do this

Author  Topic 

helixpoint
Constraint Violating Yak Guru

291 Posts

Posted - 2013-10-09 : 11:00:59
This is a function that I wrote to format a persons name and ID. I have to take into account that every parm may be empty. Is there a better way to do this SQL 2008 R2


DECLARE @LastName varchar(100) = 'Smith',
@FirstName varchar(100) = 'donna',
@MiddleInitial varchar(1) = 'L',
@NameSuffix varchar(4) = '',
@IdNum int = 12345


select
@LastName + (case when @LastName <> '' and @FirstName <> '' then ', ' else '' end) +
@FirstName + (case when @LastName + @FirstName <> '' and @MiddleInitial <> '' then ' ' else '' end) +
@MiddleInitial + (case when @LastName + @Firstname + @MiddleInitial <> '' and @NameSuffix <> '' then ' ' else '' end) +
@NameSuffix + ' (' + CAST(@IdNum as varchar) + ')'


Dave
Helixpoint Web Development
http://www.helixpoint.com

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-10-09 : 13:21:29
In SQL 2012 you can use CONCAT

In sql 2008 R2 only other option would be to use COALESCE

SELECT COALESCE(LastName + ', ','') + COALESCE(FirstName + ' ','') + COALESCE(MiddleInitial + ' ','') + '(' + CAST(IdNum AS varchar) + ')' FROM Table


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page

James K
Master Smack Fu Yak Hacker

3873 Posts

Posted - 2013-10-09 : 14:05:41
Effectively what you have done is ok. You might be able to use COALESCE and NULLIF and so on to make it look a little bit more dense, for example like shown below (which by the way, is not as comprehensive as yours)
SELECT 
COALESCE(NULLIF(@LastName,'')+', ','') +
COALESCE(NULLIF(@FirstName,'')+ ' ','') +
COALESCE(NULLIF(@MiddleInitial,'') + ' ','') +
COALESCE(NULLIF(@NameSuffix,'') + ' ','') +
COALESCE('('+NULLIF(CAST(@IdNum AS VARCHAR(32)),'')+')','')
Go to Top of Page
   

- Advertisement -