I have one table which is called #MyNames.This table in one column contain full name of persons (Name space Surname). In this column we can distinct name from surname with space with them.From left side we have name and after space we have surname.Below you can see table:
So my intention is to divided this column with name MyFullName into two separate columns called ,,FirstName" and ,,LastName''. In order to do this i try with this code:
SELECT LEFT(MyFullName,charindex(' ', MyFullName) - 1) AS FirstName, RIGHT(MyFullName,charindex(' ', MyFullName)-1 ) AS LastName
from #MyNames
Output from this code is not good and I have results like table below :
So can anybody help me how to fix this code and get result correctly and to have fist name in one column and second name in other column?
Obviously the surname clause isn't working correctly.
Instead of using RIGHT(MyFullName,charindex(' ', MyFullName)-1 ) consider SUBSTRING(MyFullName,charindex(' ', MyFullName) + 1, 100) (or whatever field length is).
A better approach (though less easy to read imo) is to replace the first name component with blank '' characters.
STUFF(MyFullName,1,charindex(' ', MyFullName),'')
These should both work
SELECT LEFT(MyFullName,charindex(' ', MyFullName)-1) AS FirstName,
SUBSTRING(MyFullName,charindex(' ', MyFullName)+1, 100) AS LastName
from #MyNames
SELECT LEFT(MyFullName,charindex(' ', MyFullName)-1) AS FirstName,
STUFF(MyFullName,1,charindex(' ', MyFullName),'') AS LastName
from #MyNames
A small correction in your query should fix the problem.
SELECT LEFT(MyFullName,charindex(' ', MyFullName) - 1) AS FirstName
, RIGHT(MyFullName,len(MyFullName) - charindex(' ', MyFullName)) AS LastName
from #MyNames
I have a column named Employee name in table 1
Example: Mr.FirstName LastName
and so on with various titles but there are employee names without the title in the same column.I am about to split the single column and do an insert in the new table (table 2) with three different columns like FirstName, LastName and Title.So while doing an insert into the new table I am not able to split the employee column name like I mentioned.Any help will be really appreciated I started with LINQ so I am not aware of much SQL functions.
Update : Sample data
Here's one example.
DECLARE #name varchar(100) = 'Mr.FirstName LastName'
SELECT
LEFT(#name, CHARINDEX('.', #name)) AS Title,
SUBSTRING(#name, CHARINDEX('.', #name)+1, CHARINDEX(' ', #name)-CHARINDEX('.', #name)) AS FirstName,
SUBSTRING(#name, CHARINDEX(' ', #name)+1, 1000) AS LastName
It takes...
the left part till the . as Title.
everything after the . until the first space as FirstName
everything after the first space as LastName
Note: There's no check for errors, if the name does not fit into this pattern.
For the simplest case you specified in the question the following query should work
SELECT *,
SUBSTRING(Employee_name, 0, CHARINDEX('.', Employee_name)) AS Title,
SUBSTRING(Employee_name,
CHARINDEX('.', Employee_name)+1,
CHARINDEX(' ', Employee_name)) AS FirstName,
SUBSTRING(Employee_name,
CHARINDEX(' ', Employee_name)+1,
LEN(Employee_name)) AS LastName
FROM Employee;
Let's say I have a table like this in SQL Server:
Id City Province Country
1 Vancouver British Columbia Canada
2 New York null null
3 null Adama null
4 null null France
5 Winnepeg Manitoba null
6 null Quebec Canada
7 Seattle null USA
How can I get a query result so that the location is a concatenation of the City, Province, and Country separated by ", ", with nulls omitted. I'd like to ensure that there aren't any trailing comma, preceding commas, or empty strings. For example:
Id Location
1 Vancouver, British Columbia, Canada
2 New York
3 Adama
4 France
5 Winnepeg, Manitoba
6 Quebec, Canada
7 Seattle, USA
I think this takes care of all of the issues I spotted in other answers. No need to test the length of the output or check if the leading character is a comma, no worry about concatenating non-string types, no significant increase in complexity when other columns (e.g. Postal Code) are inevitably added...
DECLARE #x TABLE(Id INT, City VARCHAR(32), Province VARCHAR(32), Country VARCHAR(32));
INSERT #x(Id, City, Province, Country) VALUES
(1,'Vancouver','British Columbia','Canada'),
(2,'New York' , null , null ),
(3, null ,'Adama' , null ),
(4, null , null ,'France'),
(5,'Winnepeg' ,'Manitoba' , null ),
(6, null ,'Quebec' ,'Canada'),
(7,'Seattle' , null ,'USA' );
SELECT Id, Location = STUFF(
COALESCE(', ' + RTRIM(City), '')
+ COALESCE(', ' + RTRIM(Province), '')
+ COALESCE(', ' + RTRIM(Country), '')
, 1, 2, '')
FROM #x;
SQL Server 2012 added a new T-SQL function called CONCAT, but it is not useful here, since you still have to optionally include commas between discovered values, and there is no facility to do that - it just munges values together with no option for a separator. This avoids having to worry about non-string types, but doesn't allow you to handle nulls vs. non-nulls very elegantly.
select Id ,
Coalesce( City + ',' +Province + ',' + Country,
City+ ',' + Province,
Province + ',' + Country,
City+ ',' + Country,
City,
Province,
Country
) as location
from table
This is a hard problem, because the commas have to go in-between:
select id, coalesce(city+', ', '')+coalesce(province+', ', '')+coalesce(country, '')
from t
seems like it should work, but we can get an extraneous comma at the end, such as when country is NULL. So, it needs to be a bit more complicated:
select id,
(case when right(val, 2) = ', ' then left(val, len(val) - 1)
else val
end) as val
from (select id, coalesce(city+', ', '')+coalesce(province+', ', '')+coalesce(country, '') as val
from t
) t
Without a lot of intermediate logic, I think the simplest way is to add a comma to each element, and then remove any extraneous comma at the end.
Use the '+' operator.
Understand that null values don't work with the '+' operator (so for example: 'Winnepeg' + null = null), so be sure to use the ISNULL() or COALESCE() functions to replace nulls with an empty string, e.g.: ISNULL('Winnepeg','') + ISNULL(null,'').
Also, if it is even remotely possible that one of your collumns could be interpreted as a number, then be sure to use the CAST() function as well, in order to avoid error returns, e.g.: CAST('Winnepeg' as varchar(100)).
Most of the examples so far neglect one or more pieces of this. Also -- some of the examples use subqueries or do a length check, which you really ought not to do -- just not necessary -- though your optimizer might save you anyway if you do.
Good Luck
ugly but it will work for MS SQL:
select
id,
case
when right(rtrim(coalesce(city + ', ','') + coalesce(province + ', ','') + coalesce(country,'')),1)=',' then left(rtrim(coalesce(city + ', ','') + coalesce(province + ', ','') + coalesce(country,'')),LEN(rtrim(coalesce(city + ', ','') + coalesce(province + ', ','') + coalesce(country,'')))-1)
else rtrim(coalesce(city + ', ','') + coalesce(province + ', ','') + coalesce(country,''))
end
from
table
I know it's an old question, but should someone should stumble upon this today, SQL Server 2017 and later has the STRING_AGG function, with the WITHIN GROUP option :
with level1 as
(select id,city as varcharColumn,1 as columnRanking from mytable
union
select id,province,2 from mytable
union
select id,country,3 from mytable)
select STRING_AGG(varcharColumn,', ')
within group(order by columnRanking)
from level1
group by id
Should empty strings exist aside of nulls, they should be excluded with some WHERE clause in level1.
Here is an option:
SELECT (CASE WHEN City IS NULL THEN '' ELSE City + ', ' END) +
(CASE WHEN Province IS NULL THEN '' ELSE Province + ', ' END) +
(CASE WHEN Country IS NULL THEN '' ELSE Country END) AS LOCATION
FROM MYTABLE
I have a table USERS and it has a column FULLNAME that contains full users names in the format FirstName LastName and I need to switch the data, and update it in the same column, using this format LastName, FirstName.
Ex. James Brown needs to be switched to Brown, James and updated in the same column (FULLNAME)
Is there any way to do it?
Thanks.
The best solution would be to split the elements into two columns (LastName, FirstName). However, if you want to try and squeeze it into 1 column, and you're assuming that every name is split by a single space
DECLARE #Users TABLE ( Name VARCHAR(100) )
INSERT INTO #Users
( Name
)
SELECT 'James Brown'
UNION ALL
SELECT 'Mary Ann Watson'
SELECT RIGHT(Name, CHARINDEX(' ', REVERSE(Name)) - 1) + ', ' + LEFT(Name,
LEN(Name)
- CHARINDEX(' ',
REVERSE(Name)))
FROM #Users
This also assumes that if they have more than two names sperated by a space, then the last word is the last name, and everything else is first name. Works for "Mary Ann Watson", but not "George Tucker Jones", if "Tucker Jones" is a last name.
Assuming they only have 1 space in the name:
UPDATE USERS
SET FULLNAME = RIGHT(FULLNAME,len(FULLNAME) - CHARINDEX(' ',FULLNAME)) +', '+ LEFT(FULLNAME,charindex(' ',FULLNAME)-1)
WHERE LEN(FULLNAME) - LEN(REPLACE(FULLNAME, ' ', '')) = 1
I have a select statement like
SELECT 'Name' = customer_fname+ ', ' + customer_lname
FROM customers
Its output is like:
peter, willson
jenny, Mark
Now, if customer_fname is null, then output will be:
, willson
, Mark
If customer_lname is null then:
peter,
jenny,
And if both customer_fname and customer_lname are null then only the comma will be displayed.
I want to remove the comma. How do I do this?
Ordinarily I would suggest using the ISNULL operator. However, as you need to check on both fields, the logic becomes a bit nasty. Therefore, I would suggest using a CASE statement.
SELECT CASE
WHEN first_name IS NULL AND last_name IS NULL THEN ''
WHEN first_name IS NULL AND last_name IS NOT NULL THEN last_name
WHEN first_name IS NOT NULL AND last_name IS NULL THEN first_name
ELSE last_name + ', ' + first_name
END
FROM customers
EDIT For dknaack - an ISNULL solution :)
SELECT ISNULL(last_name + ', ' + first_name,
ISNULL(last_name,
ISNULL(first_name, '')))
FROM Customers
You should use operator CASE and function ISNULL.
Please use below query: thanks
SELECT 'Name' =
(CASE WHEN customer_fname IS NULL OR customer_lname IS NULL THEN (customer_fname + ' ' + customer_lname )
ELSE customer_fname+ ', ' + customer_lname END)
FROM customers
You can use case function in SQL Server:
SELECT 'Name' = customer_fname+ case when customer_fname is not null then ',' + customer_lname FROM customers
careful with NULL values with [+] operator :
unless you set the database parameter CONCAT_NULL_YIELDS_NULL to OFF,
NULL+'any non null string' returns NULL, not empty string
SELECT ISNULL(customer_fname,'')+ ISNULL(', '+ customer_lname,'') [Name]
FROM customers