Replacing multiple items(commas, periods, etc.) in SQL code - sql

Here is the code that I am using currently, I am trying to replace commas and periods in my database but right now it is only doing one or the other. Thanks
(Case when dim.obligorname like '%,%' then Replace(DIM.[ObligorName], ',', ' ')
Else case when dim.obligorname like '%.%' then Replace(DIM.[ObligorName], '.', ' ')
Else Dim.ObligorName end end) as Obligorname,

Why not just try something like this:
UPDATE myTable DIM
SET DIM.[ObligorName] =
Replace(Replace(DIM.[ObligorName], ',', ' '), '.', ' ')

How about something like this:
Replace( Replace(DIM.[ObligorName], ',', ' '), '.', ' ')

Related

How can I CONCAT portions of three columns to one new column

I am trying to create a new column in my results that is made up on the first 3 characters of "PrimaryName", all of "VendorCity", and the first 5 characters of "VendorZip"
SELECT,VendorName
,replace(PrimaryVendorLocationName,' ','') as PrimaryName
,replace(PrimaryVendorLocationCity,' ','') as VendorCity
,replace(PrimaryVendorLocationZipCode,' ','') as VendorZip
FROM [table]
As you can see I also need to remove spaces to ensure a cleaner return. I would like to call the new column "NewVendorCode". So a record that originates like this:
R A Slack
Chicago Heights
60654-1234
Will return this:
RASChicagoHeights60654
You can use the following, using LEFT (MySQL / TSQL):
SELECT CONCAT(
LEFT(REPLACE(PrimaryVendorLocationName, ' ', ''), 3),
REPLACE(PrimaryVendorLocationCity, ' ', ''),
LEFT(REPLACE(PrimaryVendorLocationZipCode, ' ', ''), 5)
) FROM table_name
... or you can use SUBSTRING (MySQL / TSQL) (instead of LEFT):
SELECT CONCAT(
SUBSTRING(REPLACE(PrimaryVendorLocationName, ' ', ''), 1, 3),
REPLACE(PrimaryVendorLocationCity, ' ', ''),
SUBSTRING(REPLACE(PrimaryVendorLocationZipCode, ' ', ''), 1, 5)
) FROM table_name
Note: As you can see the SELECT querys work on MySQL and TSQL without change.
demo (MySQL): https://www.db-fiddle.com/f/wTuKzosFgkEuKXtruCTCxg/0
demo (TSQL): http://sqlfiddle.com/#!18/dbc98/1/1
You can use the following code:
SELECT VendorName+
replace(PrimaryVendorLocationName,' ','') +
replace(PrimaryVendorLocationCity,' ','') +
replace(PrimaryVendorLocationZipCode,' ','') as NewVendorCode
SELECT VendorName
,PrimaryName
,VendorCity
,VendorZip
,CONCAT(LEFT(PrimaryName,3),VendorCity,LEFT(VendorZip,5)) As NewVendorCode
FROM (
SELECT VendorName
,replace(PrimaryVendorLocationName,' ','') as PrimaryName
,replace(PrimaryVendorLocationCity,' ','') as VendorCity
,replace(PrimaryVendorLocationZipCode,' ','') as VendorZip
FROM [table]
)

Find value in comma-separated list

I have lists like this stored in a field in SQL:
Id MyListField
1 soy, meat, milk, wheat, nuts
2 soy, meat, nuts, milk, wheat
3 nuts
4 walnuts, nutshell, nuts
5 nuts, beans
6 walnuts, hazel nuts
7 nutshell, nutsize
This is not normalized and I can't change it. I now have to find nuts and replace them with insane (but keep e. g. hazel nuts and nutshell).
A Find is relatively easy, there are four cases and I have the placeholder character % at my disposal:
SELECT * FROM MyTable WHERE
MyListField LIKE 'nuts' OR
MyListField LIKE 'nuts, %' OR
MyListField LIKE '%, nuts' OR
MyListField LIKE '%, nuts, %'
But a Replace is hard, because I don't have placeholder or startofstring/endofstring characters:
UPDATE MyTable SET MyListField =
REPLACE(
REPLACE(
REPLACE(
REPLACE(
MyListField,
', nuts, ' ,
', insane, '
),
????,
????
),
????,
????
),
????,
????
)
WHERE
MyListField LIKE 'nuts' OR
MyListField LIKE 'nuts, %' OR
MyListField LIKE '%, nuts' OR
MyListField LIKE '%, nuts, %'
I can easily replace it in the middle of the string, but not at the start or the end. Or can I?
I am using SQL Server 2008, if that matters.
If you concatenate the field between , and _, then you only have one case to look for.
e.g.
update MyTable set MyFieldList = replace(', ' + MyFieldList + ',', ', nuts,', ', insane,')
update MyTable set MyFieldList = substring(MyFieldList, 3, len(MyFieldList) - 3)
By putting a comma at the start and end of the list, each element is wrapped in a leading ", " and a trailing ",".
Then your replace method becomes easy....
REPLACE(', ' + MyListField + ',',
', ' + #termToReplace + ',',
', ' + #replacement + ',')
Finally, strip the leading and trailing commas.
You could use something like
case
when Field = #val then #replaceVal
when Field like #val + ', %' then
#replaceVal + substring(Field, len(#val) + 1, len(Field))
when Field like '%, ' + #val then
left(Field, len(Field) - len(#val)) + #replaceVal
Just add all the remaining options, and you should be fine.
With all that help, it was easier than I thought it to be.
UPDATE MyTable
SET MyListField =
SUBSTRING(
REPLACE(
CONCAT(', ', MyListField, ', '),
', nuts, ',
', insane, '
),
3,
DATALENGTH(MyListField)+LEN('insane')-LEN('nuts')
)
WHERE CONCAT(', ',MyListField,', ') LIKE '%, nuts, %'
This works as long as there is one or zero occurrences in the string. If there can be more than one, it will fail, but this does not matter to me. If it matters to you, feel free to multiply the (LEN-LEN) part with How do you count the number of occurrences of a certain substring in a SQL varchar?

Eliminating a space in concatenated values when null

My SELECT statement reads something like this:
SELECT JKLL.LKJJ, LKJF.ASLKD, TRIM (ADDR.UNNBR) || ' ' || TRIM(ADDR.PREDIR) || ' ' ||, TRIM(ADDR.STREET)....
Where UNNBR is the address number and PREDIR is the predirection (NSEW).
When concatenating into the same column, if predir is null, I get two spaces between UNNBR and STREET, obviously.
Can I use a case statement to eliminate this space when PREDIR is null? If so, what would that syntax look like?
I sometimes do something like this for these situations:
(TSQL syntax)
SELECT
CASE WHEN ADDR.UNNBRIS IS NOT NULL THEN ADDR.UNNBR + ' ' ELSE '' END +
CASE WHEN ADDR.PREDIR IS NOT NULL THEN ADDR.PREDIR + ' ' ELSE '' END +
...
This way you only get the space if the field isn't null.
I would use ISNULL
SELECT JKLL.LKJJ, LKJF.ASLKD, TRIM(ADDR.UNNBR) + ISNULL(' ' + TRIM(ADDR.PREDIR),'') ...
A NULL value concatenated to anything yields a NULL. So something like this will work:
WITH ex as
(SELECT 'Pants' as item, null as other, 'George' as name)
SELECT COALESCE(item + ' ', '')
+ COALESCE(other + ' ', '')
+ COALESCE(name + ' ', '')
FROM ex

Concatenate and format text in SQL

I need to concatenate the City, State and Country columns into something like City, State, Country.
This is my code:
Select City + ', ' + State + ', ' + Country as outputText from Places
However, because City and State allow null (or empty) value, what happen is, (for example) if the City is null/empty, my output will look like , Iowa, USA; or say the State is empty, then the output will look like Seattle, , USA
Is there anyway I can format the output and remove "unnecessary" commas?
Edited: Because of the requirements, I should not use any other mean (such as PL/SQL, Store Procedure) etc., so it has to be plain SQL statement
select
isnull(City, '') +
case when isnull(City, '') != '' then ', ' else '' end +
isnull(State, '') +
case when isnull(State, '') != '' then ', ' else '' end +
isnull(Country, '') as outputText
from
Places
Since adding a string with null will result null so if they are null (not empty string) this will give you teh desired result
Select isnull(City + ', ','') + isnull(State + ', ' ,'') + isnull(Country,'') as outputText from Places
Use the COALESCE (Transact-SQL) function.
SELECT COALESCE(City + ', ', '') + COALESCE(State + ', ', '')...
In SQL Server 2012 you can use CONCAT function:
select concat(City,', ',State,', ',Country ) as outputText from Places
Not elegant by any means...
first changes city, state,country to null values if blank
then interprets that value for null and adds a space before a comma
then replaces any space comma space ( , ) with empty set.
Query:
SELECT replace(coalesce(Replace(City,'',Null),' ') + ', ' +
coalesce(Replace(State,'',Null), ' ' + ', ' +
coalesce(replace(Country,''Null),''), ' , ','') as outputText
FROM Places
Assumes no city state or country will contain space comma space.

What's the shortest TSQL to concatenate a person's name which may contain nulls

3 fields: FirstName, MiddleName, LastName
Any field can be null, but I don't want extra spaces. Format should be "First Middle Last", "First Last", "Last", etc.
LTRIM(RTRIM(
LTRIM(RTRIM(ISNULL(FirstName, ''))) + ' ' +
LTRIM(RTRIM(ISNULL(MiddleName, ''))) + ' ' +
LTRIM(ISNULL(LastName, ''))
))
NOTE: This won't leave trailing or leading spaces. That's why it's a little bit uglier than other solutions.
Assuming by "extra spaces", you mean extra spaces inserted during the concatenation (which is a reasonable assumption, I think. If you have extra spaces in your data, you should clean it up):
ISNULL(FirstName + ' ', '') + ISNULL(MiddleName + ' ', '') + ISNULL(LastName, '')
works, since you'll add a space to the name - which if it's NULL yields NULL - which yields empty string.
Edit: If you don't count the SET OPTION - which can be a connection or db option:
SET CONCAT_NULL_YIELDS_NULL OFF
LTRIM(FirstName + ' ' + NULLIF(MiddleName + ' ', ' ') + LastName)
is a tiny bit shorter, but a large bit uglier.
Edit2: Since you accepted the UDF answer - IMO, that's a bit of a cheat - here's some in the same vein:
SELECT a FROM b
b is a view. ;) Or. a stored proc,
EXEC c
But, since EXEC is optional:
c
use a UDF:
`Select udfConcatName(First, Middle, Last) from foo`
That way all your logic for concatenating names is in one place and once you've gotten it written it's short to call.
LTRIM(RTRIM(ISNULL(FirstName, '') + ' ' + LTRIM(ISNULL(MiddleName, '') + ' ' +
ISNULL(LastName, ''))))
Why not use a computed column on the table that performs the concat for you using your preferred syntax from the many posted here? Then you will just query the computed column - very elegant and if you persist the computed column then you may even get slight performance increase.
Example here
replace(ltrim(rtrim(isnull(FirstName, '') + ' ' + isnull(MiddleName, '') + ' ' + isnull(LastName, ''))), ' ', ' ')
'"' + ltrim(rtrim(isnull(FirstName,''))) + ' ' + ltrim(rtrim(isnull(MiddleName,''))) +
' ' + ltrim(rtrim(isnull(LastName,''))) + '","' + ltrim(rtrim(isnull(FirstName,''))) +
' ' + ltrim(rtrim(isnull(LastName,''))) + '","' + ltrim(rtrim(isnull(LastName,''))) +
'"'
ETC
DECLARE #first varchar(10) = 'First'
DECLARE #middle varchar(10) = ''
DECLARE #last varchar(10) = 'Last'
LTRIM(RTRIM(
#first
+ ISNULL(NULLIF(' '+LTRIM(RTRIM(#middle)),' '),'')
+ ISNULL(NULLIF(' '+LTRIM(RTRIM(#last)),' '),'')
))
WHY THIS WORKS
The fields are reduced to an empty string if NULL or whitespace by the LTRIM, RTRIM, and ISNULL functions.
LTRIM(RTRIM(ISNULL(#middle,''))) -- Result is a trimmed non-null string value.
That value is prefixed with a single space, then compared to a single space by the NULLIF function. If equal, a NULL results. If not equal, then the value is used.
NULLIF(' '+'',' ') -- this would return NULL
NULLIF(' '+'Smith',' ') -- this would return ' Smith'
Finally, ISNULL() is used to convert the NULL passed by NULLIF to an empty string.
ISNULL(NULL,'') -- this would return ''
ISNULL(' Smith','') -- this would return ' Smith'
LTrim(RTrim(Replace(IsNull(Firstname + ' ', '') +
isNull(MiddleName, '') +
IsNull(' ' + LastName, ''), ' ', ' ')))
Select firstname, middlename, lastname, ProvidedName =
RTrim(Coalesce(FirstName + ' ','')
+ Coalesce(MiddleName + ' ', '')
+ Coalesce(LastName + ' ', '')
+ COALESCE('' + ' ', '')
+ COALESCE(NULL, ''))
From names