Wednesday, September 5, 2012

get rid of parts in your string in MSSQL


this little snippet will help you to get rid of parts in strings.  in this case I wanted to get rid of the domain in the following string: 'domain\user'
 


declare @UserNameWithDomain varchar(32)
set @UserNameWithDomain = 'domain\user'

select replace(@UserNameWithDomain, left(@UserNameWithDomain, PATINDEX('%\%',@UserNameWithDomain)),'') as UsernameWithoutDomain

so, the result should be 'user' 

short explanation:


  • PATINDEX will find the '\'
  • LEFT will use the string from the beginning till the '\' found by PATINDEX
  • REPLACE will replace the defined left-string in the variable @UserNameWithDomain with nothing ('')


No comments:

Post a Comment