views:

32

answers:

1

Hi All,

I am moving data from an old table to a SQL server new version and am struggling with something that hopefully someone can help with.

I have a column in the old table with 'EmployeeName' in the order firstname.lastname. In the new table we will be using a guid to identify the employees. The table with the guid's has the names in the order 'lastname, firstname' so my function that I wrote to pull the guid for the employee fails to match the names.

How can I in SQL server convert 'firstname.lastname' to 'lastname, firstname'?

here is the function I wrote:

ALTER FUNCTION [Wire].[udf_GetEmployeeGuid_FromName]
( @EmployeeName   VARCHAR(50)  -- format 'firstname.lastname')
RETURNS uniqueidentifier
AS
BEGIN
DECLARE @EmployeeGuid     uniqueidentifier
SELECT @EmployeeGuid = GUID
FROM B.Employees  --format 'lastname, firstname'
WHERE LEFT(@EmployeeName, CHARINDEX('.', @EmployeeName)) = RIGHT([Name], LEN([Name]) - CHARINDEX(', ', [Name]))
RETURN IsNull(@EmployeeGuid, '00000000-0000-0000-0000-000000000000')
END
+1  A: 

Here's a start:

You can get lastname from firstname.lastname like this:

RIGHT(EmployeeName, LEN(EmployeeName) - CHARINDEX('.', EmployeeName))

Similarly, you can get lastname from lastname, firstname like this:

LEFT((EmployeeName, CHARINDEX('.', EmployeeName))

You can concatenate the names and punctuation to get the string you want.

You might consider also using TRIM to eliminate blanks in the data.

DOK
unfortunately I am relatively new to writing these types of statements and an struggling with how to do this using the above code you provided.
bluefeet
I'm running out the door, but in short you want to SELECT guid FROM tablename WHERE LEFT((othertable.EmployeeName, CHARINDEX('.', othertable.EmployeeName)) = RIGHT(tablename.EmployeeName, LEN(tablename.EmployeeName) - CHARINDEX('.', tablename.EmployeeName)) -- you want a WHERE for both firstnames and an AND for both lastnames, using the LEFT and RIGHT syntax.
DOK
I edited the original post with the function I wrote. It is still not giving me the guid.
bluefeet
Argh! Try breaking your function down into parts and make sure they are doing what you expect. For example check what you're getting from the first part of the WHERE clause like this: SELECT TOP 100 * FROM B.Employees WHERE LEFT(@EmployeeName, CHARINDEX('.', @EmployeeName)). You may find, for example, there there is no space after the comma, or there are extra spaces in one table. Just eyeball the data. Also, I think you need to have an AND in the WHERE for the other name. That is, one clause matches firstname and the other matches lastname. Make sure you're only getting one record returned.
DOK