This is probably a simple question but I'm trying to create a new column in SQL server based off of 4 others. The idea is to create a customer ID based off the first 5 characters of Zip, Last name, first name, and address.
My question is: how to I ensure that I get a spacing buffer if the name is too short? For example, I have a guy with the first name of Tom. How to I get it to return 'TOM ' with the two spaces at the end?
NOTE: I'm fully aware that creating a customer key based off something that can change like an address can cause problems. I've discussed that with the client and they said to do it anyway.
Couple more ways
select STUFF(' ', 1, LEN(name), name)
select name + REPLICATE(' ', 5 - len(name))
left (rtrim(#str) + ' ', 5)
That's five spaces ;-)
Related
So i have data that full with name, i need to get the last name
example
name : first middle last or first last
so i need to get the last name using charindex and reverse function but i dont want the last name reversed became tasl.
sorry for my bad english
i tried using charindex to find where is the space for the last name
Charindex(' ', REVERSE(Name))
but i got no idea because i need to use substring to add more text after i got the last name
SELECT
name,
parsename(replace(name,' ','.'),1) usingParseName,
substring(name,len(name) - Charindex(' ', REVERSE(Name))+2,200) usingCharIndex
FROM person
see: DBFIDDLE
]
The name column has both first and last name in one column.
Look at the 'rep' column. How do I filter only those rep names where the last name is starting with 'K'?
The way that table is defined won't allow you to do that query reliably--particularly if you have international names in the table. Not all names come with the given name first and the family name second. In Asia, for example, it is quite common to write names in the opposite order.
That said, assuming you have all western names, it is possible to get the information you need--but your indexes won't be able to help you. It will be slower than if your data had been broken out properly.
SELECT rep,
RTRIM(LEFT(LTRIM(RIGHT(rep, LEN(rep) - CHARINDEX(' ', rep))), CHARINDEX(' ', LTRIM(RIGHT(rep, LEN(rep) - CHARINDEX(' ', rep)))) - 1)) as family_name
WHERE family_name LIKE 'K%'
So what's going on in that query is some string manipulation. The dialect up there is SQL Server, so you'll have to refer to your vendor's string manipulation function. This picks the second word, and assumes the family name is the second word.
LEFT(str, num) takes the number of characters calculated from the left of the string
RIGHT(str, num) takes the number of characters calculated from the right of the string
CHARINDEX(char, str) finds the first index of a character
So you are getting the RIGHT side of the string where the count is the length of the string minus the first instance of a space character. Then we are getting the LEFT side of the remaining string the same way. Essentially if you had a name with 3 parts, this will always pick the second one.
You could probably do this with SUBSTRING(str, start, end), but you do need to calculate where that is precisely, using only the string itself.
Hopefully you can see where there are all kinds of edge cases where this could fail:
There are a couple records with a middle name
The family name is recorded first
Some records have a title (Mr., Lord, Dr.)
It would be better if you could separate the name into different columns and then the query would be trivial--and you have the benefit of your indexes as well.
Your other option is to create a stored procedure, and do the calculations a bit more precisely and in a way that is easier to read.
Assuming that the name is <firstname> <lastname> you can use:
where rep like '% K%'
I'm sure this is probably a very simple question but I'm new to SQL and I can't find anything on the forum that addresses exactly what I'm trying to accomplish, so bear with me.
I'm working in SQL Server Report Builder. I'm setting up my Data Source and Query. The table I'm querying only has a "Full Name" field, but, on this report, I need to split it up into "First Name" and "Last Name". I'd like to do all of this directly from the Dataset->Query section, if possible. The "Full Name" field is in this format: SMITH, MARK ALEXANDER
Some people have more than one first name, so, in the example above "Mark Alexander" can become "First Name".
I've been able to get this working for the Last Name using PARSENAME as so:
SELECT DISTINCT [Zip Code]
,PARSENAME(REPLACE([Full Name], ',', '.'), 2) AS [LastName]
FROM [SomeDB].[dbo].[T_MAIN_LIVE]
...but I have not been able to get it working correctly for the First Name. I've also tried using the RIGHT command but had similar issues. It either cut off part of the first name, ignored "secondary" first names, or printed the first name with a preceding space that I can't seem to get rid of. For example, the closest I can get is with this:
SELECT DISTINCT [Zip Code]
,PARSENAME(REPLACE([Full Name], ',', '.'), 1) AS [FirstName]
FROM [SomeDB].[dbo].[T_MAIN_LIVE]
...but I'm left with a preceding space. Maybe I just need to eliminate the preceding space after the fact? If so, how should I go about that?
Again, I'm sure this is a simple fix for you SQL experts so I apologize for my ignorance.
Thanks in advance,
Cameron
You can try this. It worked for me.
SELECT name = 'smith, mark alexander'
INTO #name
SELECT concat(SUBSTRING(name, CHARINDEX(',', name, 1) + 1, 20), ' ', SUBSTRING(name, 1, CHARINDEX(',', name, 1) - 1))
FROM #name
EDIT: This assumes there is a comma separating the last from the first name in all instances.
Please assist me in explaining how the coder created this great solution, I'll briefly explain the table:
select * from people
returns the value:
name
Anibal Dorothea Tromp IV
The challenge is solved in many ways, but one solution really amazed me:
select
substring(name, '^(.+)\s\S+\s\S+$') as name,
substring(name, '^.+\s(\S+)\s\S+$') as first_lastname,
substring(name, '^.+\s(\S+)$') as second_lastname
from people
returns the result:
name first_lastname second_lastname
Anibal Dorothea Tromp IV
the real table has many more rows, some with 1 first name, others with 2 first names. So the challenge was to separate the names with the first name (name) being a different length word and sometimes more than 1 word.
If I look at the documentation on substring, there is no mention of this method, please explain to me how his great solution works or point me in the direction of a site that explains some of the components of this solution.
Many thanks,
Tim
This special string you are referring to is called a regular expression. Regular expressions are available in many RDBMS and programming languages.
Postgres does have documentation on this here: https://www.postgresql.org/docs/current/functions-matching.html
The query above, has three substring with regex patterns in them:
'^(.+)\s\S+\s\S+$' matches every group except the last two. Anibal Dorothea
'^.+\s(\S+)\s\S+$' matches the second last group Tromp
'^.+\s(\S+)$' mathces the final group IV
If you changed the input text to Anibal Dorothea Tromp the IV the output from the select above would be:
name first_lastname second_lastname
Anibal Dorothea Tromp the IV
Although you can use substring() like this -- and it is well documented -- this seems like a good use case for split_part():
select split_part(name, ' ', 1),
split_part(name, ' ', 2),
split_part(name, ' ', 3),
split_part(name, ' ', 4)
Or if you need a more advanced splitter, you can use regexp_split_to_array().
Im running a sql search query to bring up records that match a post code
say i have a postcode:
'CB4 1AB'
if the database has (with and without a space)
cb41ab
cb4 1ab
or i search with (with and without a space)
cb41ab
cb4 1ab
i want it to bring back the record
How can i do it?
select addr1, addr2, postcode
from addresses p
where p.postcode LIKE 'cb%'
Thanks
You can try something like this:
select addr1, addr2, postcode
from addresses p
where replace(p.postcode, ' ', '') LIKE 'cb41ab'
So, it sounds like you're going for this. Expanding on other answers:
DECLARE #input VARCHAR(50)
SET #input = 'CB4 1AB'
SELECT addr1, addr2, postcode
FROM addresses p
WHERE REPLACE(p.postcode, ' ', '') = REPLACE(#input, ' ', '')
EDIT: I removed the "LIKE" since this should cover all above cases.
The question is unclear to me so I have multiple answers:a) If you look for a specific UK post code, do it like this: LIKE 'cb4%1ab'. Both versions will return ("spaced" and wo. space ones).b) If you use LIKE 'cb%' that won't give any trouble either. Field will return the value either it has or has no space in it.c) If you want to find a post code, specifically having or not having space say LIKE 'cb4_1%' for post codes with space and LIKE 'cb41%' for post codes not having space - or even better to look for field size instead (6 chars long or 7) so LENGTH([fieldname]) = 6 [or 7]d) The user enters a postcode and you don't know if value has or has no space in it: I'd say code revise is needed, shouldn't be sorted out on SQL/Server side. If it's not possible REPLACE added by others is just fine. If both "d" and "a" is true in your case, use REPLACE to change space into "%", so whatever the input was and whatver is stored in db (field value has or has no space), you'll get the resultLast but not least, just an advice: if you have the chance to 'uniformize' the field's value, do it (set field max length to 6 and/or update the table and remove space from values)Hope this helps!
[EDIT: added 'd' option :) ]