SQL Server snippets

How extract the left side of a string until a character

Example 1

Assuming that we have the following table of e-mail adress #Email

CREATE TABLE #Mail(
	[Name] [nvarchar](50) NOT NULL,
	[Surname] [nvarchar](50) NOT NULL,
	[Email_adress] [nvarchar](500) NULL,
) ON [PRIMARY];
INSERT INTO #Mail
  ( [Name], [Surname], [Email_adress])
VALUES
  ('Mary', 'Green', 'mary.green@greenmail.com'),
  ('Lory', 'Red', 'lory@redmail.com'),
  ('John', 'Yellow', 'j.yellow@mail.ma'),
  ('Susan', 'De Blue', 'susy@bluemail.com');

We can find the position of the "@" sign and use this to extract anything in the left until this position

SELECT *,CHARINDEX('@',[Email_adress]) AS [Position],
LEFT([Email_adress],CHARINDEX('@',[Email_adress])-1) AS [Mail_username]
FROM #Mail
Table #Email extract

You can find an interactive version of this example following this link .

Back to SQL Server cookbook page