Adding comma after first word in column - sql

I have a table called people and a column called NAME which has last first middle (if exists) . so SMITH JOHN J I'd like to add a comma after first word so it updates to SMITH, JOHN J
I tried running this but it blew up:
update people
set name = (CHARINDEX(' ', 0), 0, ',')
I know I'm close but it's eluding me :(

You can use STUFF() along with CHARINDEX() and LEFT() for this:
update people
set name = STUFF(name,1,CHARINDEX(' ',name )-1,LEFT(name ,CHARINDEX(' ',name )-1)+', ')
WHERE CHARINDEX(' ',name) > 0
Might add a WHERE to ensure there is a space in the name so it doesn't error, or a CASE expression.
Could also use REPLACE() with CHARINDEX() and LEFT():
REPLACE(name,LEFT(name,CHARINDEX(' ',name)-1),LEFT(name,CHARINDEX(' ',name)-1)+',')

Related

Pulling a section of a string between two characters in SQL, and the section of the string around the extracted section

I have a table that includes names and allows for a "nickname" for each name in parenthesis.
PersonName
John (Johnny) Hendricks
Zekeraya (Zeke) Smith
Ajamain Sterling (Aljo)
Beth ()) Jackson
I need to extract the Nickname, and return a column of nicknames and a column of full names (Full string without the nickname portion in parenthesis). I also need a condition for the nickname to be null if no nickname exists, and so that the nickname only returns letters. So far I have been able to figure out how to get the nickname out using Substring, but I can't figure out how to create a separate column for just the name.
Select SUBSTRING(PersonName, CHARINDEX('(', PersonName) +1,(((LEN(PersonName))-CHARINDEX(')',REVERSE(PersonName)))-CHARINDEX('(',PersonName)))
as NickName
from dbo.Person
Any help would be appreciated. I'm using MS SQL Server 2019. I'm pretty new at this, as you can tell.
Using your existing substring, one simple way is to use apply.
Assuming your last row is an example of a nickname that should be NULL, you can use an inline if to check its length - presumably a nickname must be longer than 1 character? Adjust this logic as required.
select PersonName, Iif(Len(nn)<2,null,nn) NickName, Trim(Replace(Replace(personName, Concat('(',nn,')') ,''),' ','')) FullName
from Person
cross apply (values(SUBSTRING(PersonName, CHARINDEX('(', PersonName) +1,(((LEN(PersonName))-CHARINDEX(')',REVERSE(PersonName)))-CHARINDEX('(',PersonName))) ))c(nn)
The following code will deal correctly with missing parenthesis or empty strings.
Note how the first CROSS APPLY feeds into the next
SELECT
PersonName,
NULLIF(NickName, ''),
FullName = ISNULL(REPLACE(personName, ' (' + NickName + ')', ''), PersonName)
FROM t
CROSS APPLY (VALUES(
NULLIF(CHARINDEX('(', PersonName), 0))
) v1(opening)
CROSS APPLY (VALUES(
SUBSTRING(
PersonName,
v1.opening + 1,
NULLIF(CHARINDEX(')', PersonName, v1.opening), 0) - v1.opening - 1
)
)) v2(NickName);
db<>fiddle

Return anything but a space with INSTR or CHARINDEX

I need to return results where a space is NOT used in the 3rd to last position (so from the right). Attempting to identify records where a US state acronym was not used.
JOHN MN
MATT HI
TERRY ARKANSAS
I'm running this through DBVisualizer and I am stumped. I've tried to add some CHARINDEX, RIGHT...etc, but no combination is working.
Ideally, it would look something like:
SELECT INSTR(COLUMN, **<>** ' ', -3) FROM TABLE
try Something like this :
select * from yourtable
where
case when length(trim(yourcolumn))>2 and right(trim(yourcolumn), 3) like ' %' then 1 else 0 end =0
or this
select * from yourtable
where trim(yourcolumn) not like '% __'
Try this:
SELECT IIF(len(RIGHT(COLUMN,LEN(COLUMN)-3))=LEN(REPLACE(RIGHT(COLUMN,LEN(COLUMN)-3),' ','')),0,1)
If it returns 0, that means it does not have a blank value from 3rd to the last position.
If it returns 1, that means it does have a blank.

SQL Server 2008 - Remove the parentheses and anything between

I am having a hard time to figure out how to remove the parentheses and anything inside it, plus the space in front. I tried the combination of CharIndex, Substring, and LEFT, but could not get it work correctly.
Here is the example. Let's say I have a very simple table "ContactName" and a column "DisplayName"
Query would be "Select DisplayName FROM ContactName".
In the ContactName table, the data looks like this:
Joe Blow (joe.blow#yahoo.com)
John Deep (jdeep#gmail.com)
(Tim.King#gmail.com) King, Timothy
Richard Harris
Wang, Justin
What I would like to do is removing anything with the parenthesis including the space in front of it if any. For example, "Joe Blow (joe.blow#yahoo.com)" will become "Joe Blow" with NO space, not "Joe Blow ". Also, "(Tim.King#gmail.com) King, Timothy" will become "King, Timothy"
Example of the result would be like this, and NO trailing spaces after the name.
Joe Blow
John Deep
King, Timothy
Richard Harris
Wang, Justin
Maybe I need some kind of RegEx to accomplish this. Please help.
Thanks in advance,
To remove all characters between ( and ) in the string (if they are present), you can use stuff and then a combination of ltrim and rtrim to remove all the trailing and leading spaces.
case when charindex('(',displayname) > 0 and charindex(')',displayname) > 0
then rtrim(ltrim(stuff(displayname,charindex('(',displayname),charindex(')',displayname),'')))
else displayname end
Here is one rather brute force way that works when the parentheses are either at the beginning or end:
select (case when displayname like '(%'
then stuff(displayname, 1, charindex(') ', displayname + ') '), '')
when displayname like '%)'
then left(displayname, charindex(' (', displayname + ' ('))
else displayname
end)
Not an idea solution, but SQL Server doesn't have great support for strings.
Here's another approach:
DECLARE #Table TABLE (DisplayName VARCHAR(100))
INSERT INTO #Table
VALUES ('Joe Blow (joe.blow#yahoo.com)'),
('John Deep (jdeep#gmail.com)'),
('(Tim.King#gmail.com) King, Timothy'),
('Richard Harris'),
('Wang, Justin')
SELECT RTRIM(
LTRIM(
REPLACE(DisplayName,
SUBSTRING( DisplayName,
CHARINDEX('(',DisplayName,1),
((CHARINDEX(')',DisplayName, 1)) - (CHARINDEX('(',DisplayName,1))+1)
),
'')
)
)
FROM #Table

SQL- Remove Trailing space and add it to the beginning of the Name

Was working on SQL-EX.ru exercises.
There is one question for DML that I could not do, but I cannot proceed to the next one, until this one is done.
the question itself: All the trailing spaces in the name column of the Battles table remove and add them at the beginning of the name.
My code:
Update Battles
set name=concat(' ',(LTRIM(RTRIM(name))))
The system does not let it go through, I understand that I am using ' ' for the concat, whereas I need to use the stuff that got trimmed. And I have no idea how...
Any help would be very much appreciated
Try Something Like:-
set name = lpad(trim(name), length(trim(name))+4, ' ')
Here use TRIM to remove space from both side. use LPAD to add something on left side with n (4) chars
I'm not familiar with SQL-EX.ru, but if it's Oracle compatible and you can use regular expressions (or you are at that point in the training) here's a way. Maybe it'll give you an idea at least. The first part is just setup and uses a WITH clause to create a table (like a temp table in memory, actually called a Common Table Expression or CTE) called battles containing a name column with 2 rows. Each name column datum has a different number of spaces at the end. Next select from that column using a regular expression that uses 2 "remembered" groups surrounded by parentheses, the first containing the string up to until but not including the first space, the second containing 0 or more space characters anchored to the end of the line. Replace that with the 2nd group (the spaces) first, followed by the first group (the first part of the string). This is surrounded by square brackets just to prove in the output the same spaces were moved to the front of the string.
SQL> with battles(name) as (
select 'test2 ' from dual union
select 'test1 ' from dual
)
select '[' || regexp_replace(name, '(.*?)([ ]*)$', '\2\1') || ']' fixed
from battles;
FIXED
----------------------------------------------------------------------------
[ test1]
[ test2]
SQL>
I hope this solution can be applied to your problem or at least give you some ideas.
Try this:
set name = case when len(name) > len(rtrim(name))
then replicate(' ', len(name) - len(rtrim(name))) + rtrim(name)
else name
end
update battles
set name = case when (len(name+'a')-1) > len(rtrim(name))
then
replicate(' ',
(len(name+'a')-1) - len(rtrim(name))) + rtrim(name)
else name
end
Len() doesn't count trailing spaces. So using (len(name+'a')-1).
Simplest answer:
UPDATE Battles
SET name = SPACE(DATALENGTH(name)-DATALENGTH(RTRIM(name))) + RTRIM(name)
But only works because name is VARCHAR.
More generic is to do:
UPDATE Battles
SET name = SPACE(len(name+'x')-1-len(RTRIM(name))) + RTRIM(name)
simple example below ... enjoy :)
update battles set name =
Space( DATALENGTH(name) - DATALENGTH(rtrim(name))) + rtrim(name)
where date in ( select date from battles)

How do I trim out middle initial from a person's full name in SQL?

I'm look for the simplest way to split up first and last name wile trimming out the middle initial. The current layout of the field is [Last Name], [First Name] [MI]. Also, middle initial is not always there. My current code is below, I'm just not sure how to trim out the middle initial from first name without writing a case statement.
SELECT SUBSTRING(h.Name, CHARINDEX(',', h.Name, 0) + 2, LEN(h.Name) - CHARINDEX(',', h.Name, 0)), 0 as FirstName
,SUBSTRING(h.Name, 0, CHARINDEX(',', h.Name, 0)) as LastName
FROM Members
I have made some assumptions below:
1 - First names are always longer than one character.
2 - Middle inital will always be preceded by a space.
3 - The data is trimmed.
This code will return NULL if any of the above are not true. If your data is not trimmed, you can use RTRIM on all instances of #n below to mitigate.
declare #n as varchar(50)
set #n = 'Smith, John A'
select #n,
case
when SUBSTRING(#n, LEN(#n) - 1, 1) = ' '
then SUBSTRING(#n, LEN(#n), 1)
end
What are the business rules of this system? Will it always be:
last name , first name space a possible middle initial
What other permutations can exist?
Will it always be space letter . ? Because then you could always take the right three characters, look for a space and a period, then remove the set of three.
select REPLACE(firstName+ISNULL(middleName+' ','')+ISNULL( lastName +' ',''),' ',' ') as 'name' from Contacts