Dividing a string into two parts and selecting into two variables

I am using SQL Server 2005. I have a string with a special character : like:

XYZ:xyz@mail.com

I want to divide this string into two sub-strings and select into variables. The special character : is just a separator.

@variable1=XYZ
@variable2=xyz@mail.com

Please guide me on how it is possible.

DECLARE @string varchar(max), @variable1 varchar(max), @variable2 varchar(max);
SET @string = 'XYZ:xyz@mail.com';

SELECT
  @variable1 = SUBSTRING(S, 1, P - 1),
  @variable2 = SUBSTRING(S, P + 1, L - P)
FROM (
  SELECT
    S = @string,
    P = CHARINDEX(':', @string),
    L = LEN(@string)
) s;

SELECT @variable1, @variable2;
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s