How do I replace a substring of a string before a specific character? - sql

Table Email:
Values:
josh#yahoo.com
carmine32#hotmail.com
zehmaneh#yahoo.com
I want to replace the string before # with test.
Result:
test#yahoo.com
test#hotmail.com
test#yahoo.com
How do I use substringing and replace based on a character in the string?

You don't even need to use substring or replace, you can use this:
SELECT 'test' + RIGHT(email, charindex('#', REVERSE(email)))
FROM YourTable
You can test it out with this:
DECLARE #email nvarchar(50)
SET #email = 'carmine32#hotmail.com'
PRINT 'test' + RIGHT(#email, charindex('#', REVERSE(#email)))

declare #t table(email varchar(30))
insert #t values('josh#yahoo.com'),
('carmine32#hotmail.com'),
('zehmaneh#yahoo.com')
select stuff(email, 1, charindex('#', email), 'Test#')
from #t
Result:
Test#yahoo.com
Test#hotmail.com
Test#yahoo.com

You can use SUBSTRING and CHARINDEX:
UPDATE Email set email =
'test' + SUBSTRING(email, CHARINDEX('#',email), LEN(email))
Fiddle: http://sqlfiddle.com/#!3/0face/6/0

You could
select 'test' + substring(fld, charindex('#', fld), len(fld))

Related

How to select only the domain name from the Email using SQL Server Query

I have an email address like venugopal#yahoo.com,venugopal#gmail.com,venugopal#hotmail.com etc;
I want the output like yahoo,gmail,hotmailetc; only the domain names
can anyone help me with a SQL Server query.
You can get everything after the at-sign by using stuff():
select stuff(email, 1, charindex('#', email) , '') as domain
Try this:
DECLARE #DomainNames VARCHAR(8000)
SELECT #DomainNames = COALESCE(#DomainNames + ',', '') + STUFF(REPLACE(email,'.com',''), 1, charindex('#', REPLACE(email,'.com','')) , '')
FROM YOUR_TABLE_NAME
SELECT #DomainNames
I think you want :
select t.*,
substring(col, charindex('#', col)+1, len(col)) as domain
from table t;
EDIT :
If you want only domain name then you can do :
select t.*, left(domain, charindex('.', domain) - 1) as domain
from table t cross apply
( values (substring(col, charindex('#', col)+1, len(col)))
) tt(domain);
Dubble stuff, first remove up until # and then remove after . and to the end
declare #email varchar(100);
set #email = 'venugopal#yahoo.com';
select stuff(domain, charindex('.', domain), len(domain)-1, '')
from (select stuff(#email, 1, charindex('#', #email) , '') as domain) x

SQL Server remove part of string between characters

I have emails that look like this:
john.doe.946a9979-2951-4852-9e79-ad03eb0c1e5d#gmail.com
I am trying to get this output:
john.doe#gmail.com
I have this so far.... it's close.
SELECT
Caller = REPLACE(Caller,
SUBSTRING(Caller,
CHARINDEX('.', Caller),
CASE WHEN CHARINDEX('#', Caller, CHARINDEX('.', Caller)) > 1 THEN
CHARINDEX('#', Caller, CHARINDEX('.', Caller)) - CHARINDEX('.', Caller)
ELSE
LEN(Caller)
END ) , '')
FROM
some.table
Hmmm. I suspect the string you want to remove is fixed in length. So how about:
select stuff(caller, charindex('#',caller ) - 37, 37, '')
If you have SS 2016 or later, you can use R code to do it - granted I don't know about speed on larger data so be wary if its a production environment. Also be warned Regexp isn't my strongest area so you may want to check that portion.
DECLARE #dummyScript NVARCHAR(1000) = '
SELECT * FROM
(VALUES (''john.doe.946a9979-2951-4852-9e79-ad03eb0c1e5d#gmail.com''),
(''jane whoever 1234453-534343#yahoo.com'') ) t (Email)
'
DECLARE #myRcode NVARCHAR(600)
SET #myRcode = 'OutputDataset <- data.frame(Email_Cleaned = gsub("[0-9]+.+#", "#", InputDataSet$Email)) '
DECLARE #CleanedTable TABLE (Email_Cleaned VARCHAR(500))
INSERT INTO #CleanedTable
EXEC sp_execute_external_script
#language = N'R'
,#script = #myRcode
,#input_data_1 = #dummyScript
,#input_data_1_name = N'InputDataSet'
,#output_data_1_name = N'OutputDataset'
SELECT * FROM #CleanedTable
Here is a simpler method using LEFT(), RIGHT(), and CHARINDEX() functions
DECLARE #Caller VARCHAR(MAX) = 'john.doe.946a9979-2951-4852-9e79-ad03eb0c1e5d#gmail.com'
SELECT
LEFT(#Caller, CHARINDEX('.', #Caller, CHARINDEX('.', #Caller) + 1) - 1) + RIGHT(#Caller, LEN(#Caller) - CHARINDEX('#', #Caller) + 1) Email
The left side will get all the characters until the second dot, and the right side will get the characters from # sign to the end of characters.
Try like below
SELECT
REPLACE(CALLER,
Substring(CALLER,
PATINDEX('.[0-9]%#', CALLER),
PATINDEX('#', CALLER ) )
,'#')
From Table

replacing letter in email address before # SQL

I am trying to update the email address field. My Scenario is I have column containing email address and I want the replace to work on the string before '#'. Before '#' if the character is 'a', I want it to be replaced with 'b'.
for davidsmith#yahoo.com the result would be dbvidsmith#yahoo.com
Thank you
DECLARE #email VARCHAR(1000) = 'davidsmith#yahoo.com'
SELECT
REPLACE(SUBSTRING(#email,0,e.t),'a','b')+
SUBSTRING(#email,e.t,8000)
FROM (VALUES (CHARINDEX('#',#email))) e(t);
Returns:
dbvidsmith#yahoo.com
You can use charindex() :
select replace(substring(email, 1, charindex('#', email)-1), 'a', 'b') +
substring(email, charindex('#', email), len(email))
from table t
where email like '%#%' -- or
charindex('#', email) > 0;

Select only characters in SQL

I have strings in a database like this:
firstname.lastname#email.com
And I only need the characters that appear after the # symbol and before (.) symbol i.e. (email) from the above example
I am trying to find a simple way to do this in SQL.
Do this:
use [your_db_name];
go
create table dbo.test
(
string varchar(max) null
)
insert into dbo.test values ('firstname.lastname#email.com')
select
string,
substring(
string,
charindex('#', string, 0) + 1,
charindex('.', string, charindex('#', string, 0)) - charindex('#', string, 0) - 1
) as you_need
from dbo.test
String manipulations are such a pain in SQL Server. Here is one method:
select t.*,
left(en.emailname, charindex('.', en.emailname + '.') - 1)
from t outer apply
(select stuff(email, 1, charindex('#', email + '#'), '') as emailname) en;
That that in the charindex() calls, the character being searched for is placed at the end of the string. This allows the code to work even for malformed emails -- it returns an empty string when the email is not of the form '%#%.%'.
DECLARE #col char(200)
set #col = 'firstname.lastname#email.com'
SELECT SUBSTRING(#col, LEN(LEFT(#col, CHARINDEX ('#', #col))) + 1, LEN(#col) - LEN(LEFT(#col, CHARINDEX ('#', #col))) - LEN(RIGHT(#col, LEN(#col) - CHARINDEX ('.', #col))) - 4);
DECLARE #str varchar(50) = 'firstname.lastname#email.com';
SELECT LEFT(
RIGHT(#str, LEN(#str) - CHARINDEX('#', #str))
,CHARINDEX('.', RIGHT(#str, LEN(#str) - CHARINDEX('#', #str))
) - 1) AS OUTPUT
Above query gives only domain-name from Email. The query can be applied for column in a table
Try This:-
DECLARE #Text varchar(100)
SET #Text = 'firstname.lastname#email.com'
SELECT SUBSTRING(STUFF(#Text, 1, CHARINDEX('#',#Text), ''), 0,
CHARINDEX('.', STUFF(#Text, 1, CHARINDEX('#',#Text), '')))
Result:-
email
DECLARE #myStr varchar(100) = 'firstname.lastname#email.com'
SELECT
SUBSTRING(SUBSTRING(#myStr,CHARINDEX('#',#myStr)+1,LEN(#myStr)-CHARINDEX('#',#myStr)+1),0,CHARINDEX('.',SUBSTRING(#myStr,CHARINDEX('#',#myStr)+1,LEN(#myStr)-CHARINDEX('#',#myStr)+1)))
That can be useful but I really recommend you to build user defined function in C#/Visaul basic they could be much more faster that this.
Using charindex, len and reverse to search for the positions of the # and the last dot.
And substring to get the name based on those positions:
create table test (id int identity(1,1), email varchar(60));
insert into test (email) values
('jane.doe#email.com'),
('not an email'),
('#invalid.email.xxx'),
('john.doe#longer.domainname.net');
select *,
(case
when email like '[a-z]%#%.%'
then substring(email,
charindex('#',email)+1,
len(email) - charindex('#',email) - charindex('.',reverse(email))
)
end) as email_domain_without_extension
from test;
The CASE WHEN is used to return NULL when it's not an email (instead of an empty string).

Splitting value of a varchar column into two columns

If I have a column in which strings vary in length but they ALL have a slash \ within,
how can I SELECT to have one column display everything BEFORE the \ and another column displaying everything AFTER the \?
name column1 column2
DB5697\DEV DB5697 DEV
I have seen CHARINDEX and REVERSE on MSDN but haven't been able to put together a soltuion.
How can I best split a varchar/string column value into 2 columns in a result set in TSQL ?
what about using PARSENAME function in a tricky way?
USE tempdb;
GO
CREATE TABLE #names
(
id int NOT NULL PRIMARY KEY CLUSTERED
, name varchar(30) NOT NULL
);
GO
INSERT INTO #names (id, name)
VALUES
(1, 'DB5697\DEV'),
(2, 'DB5800\STG'),
(3, 'DB5900\PRD');
GO
SELECT
name
, PARSENAME(REPLACE(name, '\', '.'), 2) AS [Server]
, PARSENAME(REPLACE(name, '\', '.'), 1) AS [Instance]
FROM
#names;
GO
DROP TABLE #names;
GO
The PARSENAME function accepts 2 parameters and gets the name part of a fully qualified name. The second parameter is the part name enumerator.
Value 2 is for SCHEMA and 1 is for OBJECT.
So, with the REPLACE function the "\" char is replaced by "." in order to have a SCHEMA.OBJECT format of your SERVERNAME\INSTANCE values. Then, PARSENAME behave like having a simple object name in the string.
How about the following (SQL Fiddle):
SELECT m.name,
LEFT(m.name, CHARINDEX('\', m.name) - 1) AS column1,
RIGHT(m.name, LEN(m.name) - CHARINDEX('\', m.name)) AS column2
FROM MyTable m
How to handle strings with no \ in them (SQL Fiddle):
SELECT m.name,
CASE WHEN CHARINDEX('\', m.name) = 0 THEN ''
ELSE LEFT(m.name, CHARINDEX('\', m.name) - 1) END AS column1,
CASE WHEN CHARINDEX('\', m.name) = 0 THEN ''
ELSE RIGHT(m.name, LEN(m.name) - CHARINDEX('\', m.name)) END AS column2
FROM MyTable m;
You can use CHARINDEX to check for the character position of the splitter ('/') and use SUBSTRING to split the string.
However care has to be taken to ensure you handle records without splitters else you would invoke an error.
Also in the case where splitter is unavailable, decision has to be made as to which column the data should be mapped to. Here I am mapping data to FirstName and assigning NULL to LastName
DECLARE #TableBuyer TABLE (ID INT, FullName VARCHAR(100))
INSERT INTO #TableBuyer
SELECT '1','Bryan/Greenberg' UNION ALL
SELECT '2','Channing/Tatum' UNION ALL
SELECT '3','Paul/William' UNION ALL
SELECT '4','EricBana' UNION ALL
SELECT '5','James/Lafferty' UNION ALL
SELECT '6','Wentworth/Miller'
SELECT
CASE
WHEN CHARINDEX('/', FullName) > 0 THEN SUBSTRING(FullName, 1, CHARINDEX('/', FullName) - 1)
ELSE FullName
END AS FirstName
,
CASE
WHEN CHARINDEX('/', FullName) > 0 THEN SUBSTRING(FullName, CHARINDEX('/', FullName) + 1, LEN(FullName))
ELSE NULL
END AS LastName
FROM #TableBuyer;
DECLARE #TableBuyer TABLE (ID INT, FullName VARCHAR(100))
INSERT INTO #TableBuyer
SELECT '1','Bryan/Greenberg' UNION ALL
SELECT '2','Channing/Tatum' UNION ALL
SELECT '3','Paul/William' UNION ALL
SELECT '4','EricBana' UNION ALL
SELECT '5','James/Lafferty' UNION ALL
SELECT '6','Wentworth/Miller'
select left(FullName, len(FullName)-CHARINDEX('/', REVERSE(FullName))) as firstname,
substring(FullName, len(FullName)-CHARINDEX('/', REVERSE(FullName))+ 2, len(FullName)) as lastname
from #TableBuyer
OR
select left(FullName, len(FullName)-CHARINDEX('/', REVERSE(FullName))) as firstname,
RIGHT(FullName, len(FullName)-CHARINDEX('/', FullName)) as lastname
from #TableBuyer
There is no "simple" method. Something like this should work:
select left(col, charindex('\', col) - 1) as column1,
right(col, charindex('\', reverse(col)) - 1) as column2
You might need to double up on the backslash ('\\') to get it to work properly.