Last Name First Name Switch with hyphenated names - sql

I know this has been asked several times and I have been able to find a partial answer using the results I have found on StackOverflow. I have a column that contains the name combination of "LastName FirstName" I need the row to display "FirstName LastName. I can make that happen using this SQL code:
SELECT
SUBSTRING('First Last', CHARINDEX(' ', 'First Last') + 1, 8000) +' '+
SUBSTRING('First Last', 1, CHARINDEX(' ', 'First Last') - 1) AS Name
Now when I try to use this code using my data with this code:
SUBSTRING(Rtrim(Ltrim(name)), CHARINDEX(' ', Rtrim(Ltrim(name))) + 1,
8000) +' '+ SUBSTRING(Rtrim(Ltrim(name)), 1, CHARINDEX(' ',
Rtrim(Ltrim(name))) - 1) AS Name
FROM
VW_MyView
I get my expected results but I also get an error message that states
Invalid length parameter passed to the LEFT or SUBSTRING function.
I have tracked the error down to names that have a hyphen. How can I deal with those hyphen during this process

Hmmm . . .
If you have only one or two names separated by a space:
select (stuff(name, 1, charindex(' ', name + ' ') - 1, '') + ' ' +
left(name, charindex(' ', name + ' ') - 1)
)
Note that this appends a space so the charindex() returns a valid position.

Related

SQL: Extract a word from a string

I have a following SQL statement that looks for a certain word after the keyword "dispatch level:".
SELECT SUBSTRING(CadRemarks, CHARINDEX('dispatch level:', CadRemarks) + LEN('dispatch level:'), 6) as
data
from myTable
I would like to upgrade this statement in a way that will return whatever comes between the keyword "dispatch level:" and anything that comes after the word that I'm looking for. So it could be another word, character, or space. For example:
Dispatch level: XXXXX YYY
or
Dispatch level: XXXXX
Only return XXXXX
EDIT
I'm trying out this SQL, but it selects the word after the word I need, as well.
select left(tt.CadRemarks, charindex(' ', tt.CadRemarks+ ' ')) as data
from myTablet cross apply
( values (substring(CadRemarks, charindex('dispatch level:', CadRemarks) +
16, len(CadRemarks)))
) tt(CadRemarks)
where t.CadRemarks like '%dispatch level:%'
the where clause is for me to limit the records, but I will have to move it and make the whole thing as CASE statement. But that's later....
Also tried this, but getting an error (invalid length parameter passed to the left...)
SELECT SUBSTRING(CadRemarks, CHARINDEX('dispatch level: ', CadRemarks) +
LEN('dispatch level: ') + 1,
CHARINDEX('', CadRemarks) - (CHARINDEX('dispatch level: ', CadRemarks) + 2 +
LEN('dispatch level: ')))
FROM myTable
Use left() to further find the string :
select left(tt.CadRemarks, charindex(' ', tt.CadRemarks+ ' ')) as data
from table t cross apply
( values (substring(CadtRemarks, charindex('dispatch level:', CadRemarks) + 16, len(CadRemarks)))
) tt(CadRemarks);

SQL Server : separate first and last name and remove middle initial into just two columns

I have a column that has an individuals full name, including the middle initial. I am trying to separate the full name into just first name and last name and eliminating the middle name/initial. Some of the names in my database have a middle name/initial and some don't. The following query's are what I am using and they both do only half the trick.
Query #1: returns the first name and middle name/initial in the 2nd column and eliminates the last name:
FirstName = LEFT(fullname, CHARINDEX(' ', fullname)),
LastName = RIGHT(fullname, CHARINDEX(' ', REVERSE(fullname)))
Query #2: returns the first name and combines the middle name/initial with the last name (with a space between the two):
FirstName = left(fullname,CHARINDEX(' ',fullname)),
LastName = SUBSTRING(fullname, CHARINDEX(' ',fullname)+1,LEN(fullname)-(CHARINDEX(' ',fullname)-1))
How about this?
select left(fullname, charindex(' ', fullname + ' ') - 1) as firstname,
right(fullname, charindex(' ', reverse(fullname) + ' ') - 1) as lastname
Note this handles names with no spaces without giving an error. However, the first and last name are the same (the full string). It is unclear what you want to do in this case.

SELECT DISTINCT is omitting NULL values when not desired

I am trying to build a distinct string in a query, which works unless one of the values is NULL. I've tested removing LOCATION_ADDR_LINE_2, and the query will work just fine. When I do not SELECT DISTINCT, I find that LOCATION_ADDR_LINE_2 values are NULL. How can I gather these values in the SELECT DISTINCT even if NULL?
SELECT DISTINCT(LOCATION_ADDR_LINE_1 + ', ' + LOCATION_ADDR_LINE_2 + ', ' + LOCATION_CITY + ', ' + LOCATION_WORK_STATE) AS Addresses
FROM OracleReport
WHERE (LOCATION_ADDR_LINE_1 LIKE '%1135 Auto%' OR LOCATION_ADDR_LINE_1 LIKE '%199 Easy%')
Returns:
Addresses
NULL
SELECT DISTINCT(LOCATION_ADDR_LINE_1 + ', ' + LOCATION_CITY + ', ' + LOCATION_WORK_STATE) AS Addresses
FROM [OperationReport].[dbo].[OracleReport]
WHERE (LOCATION_ADDR_LINE_1 LIKE '%1135 Auto%' OR LOCATION_ADDR_LINE_1 LIKE '%199 Easy%')
Returns:
Addresses
1135 Auto...
189-199 Easy...
Assuming you don't mind text,,text,... (empty string) when a value is NULL...
SELECT DISTINCT(coalesce(LOCATION_ADDR_LINE_1,'') + ', ' +
coalesce(LOCATION_ADDR_LINE_2,'') + ', ' +
coalesce(LOCATION_CITY,'') + ', ' +
coalesce(LOCATION_WORK_STATE,'')) AS Addresses
FROM OracleReport
WHERE (LOCATION_ADDR_LINE_1 LIKE '%1135 Auto%'
OR LOCATION_ADDR_LINE_1 LIKE '%199 Easy%')
Coalesce will take the first non-null value and return it. It requires consistent data types and will early exit once the first non-null value in a series is encountered. (more details Oracle Differences between NVL and Coalesce)

MS SQL 2012 remove repeated characters from only Right and Left

I need stripe repeated characters from left and right only.
From:
,,,,2000001,2000002,2000003,2000004,2000005,2000006,,,,,
To:
2000001,2000002,2000003,2000004,2000005,2000006
Cheat with trim:
REPLACE(RTRIM(LTRIM(REPLACE(fld, ',', ' '))), ' ', ',')
Use LEFT, SUBSTRING and CHARINDEX string functions
Try this
DECLARE #str VARCHAR(500) = ',,,,2000001,2000002,2000003,2000004,2000005,2000006,,,,,'
SELECT LEFT(intr, Charindex(',,', intr) - 1) as Result
FROM (SELECT Substring(#str, Patindex('%[0-9]%', #str), Len(#str)) AS intr) a
Here is another solution using just REPLACE :) - so funny:
select replace(replace(replace(',,' + YourField + ',,', ',,', '.'), '.,', ''), '.', '')
The character . should not be present in the value of your field, so you can choose any other character meeting that requirement.
This approach is even usable when your field contains spaces (then you cannot play the trick with RTRIM and LTRIM).

String Concatenation with comma

I am trying to build the string with comma but I get extra space. How can I remove extra space between zipcode and country_name? Here is my string. Thank you for any suggestion.
SELECT
(COALESCE(address + ', ', '') +
COALESCE(city + ', ', '') +
COALESCE(state_code + ' ', '') +
COALESCE(zipcode + ' ', '') +
COALESCE(country_name + '', '')) address
from table1
where a_id = 2
Here is the result:
tewt, test ct, DE 4444 United States
You can use the RTRIM function which remove white space from right side of the variable. Check also LTRIM for the left cases.
I would change table column datatape to varchar(x) from char(x) or to nvarchar(x) from nchar(x). And change the data so they dont contain spaces. Just have to do that once and make changes so that app is not storing white spaces anymore.
char(x) and nchar(x) i would use just when there is fixed length strings, but this does not seem to be the case.