String replacement with LIKE and % - sql

my Settings table has 2 columns: Key, Value. Both are strings.
What I am trying to do is finding a smart way to create one single SQL statement that changes the string inside Value according to what's inside.
For example, Value can contain:
'wo, find, search'
OR
'find, wo, search'
OR
'find, search, wo'
What I want to do in all 3 cases is using one SQL script to replace 'wo' with an empty string. What I created so far is:
update Settings set Value = replace(Value, 'wo, ', '')
where Key = 'SelectFeature'
update Settings set Value = replace(Value, ', wo', '')
where Key = 'SelectFeature'
update Settings set Value = replace(Value, 'wo', '')
where Key = 'SelectFeature'
as you can see it's not very elegant. Can I somehow use the operator LIKE and % to achieve this? Thanks in advance!

Still not the best solution but a more optimal way would be to do
UPDATE
Settings
SET
Value = REPLACE(
REPLACE(
REPLACE(Value, 'wo, ', ''), ', wo', ''
), 'wo', ''
)
WHERE
Key = 'SelectFeature'
This way you only run one query where you do all the changes... Update queries cost a lot of process time...

Related

I want to update a string in a table

I have a table, content_history with a column, doc_filename, and each row has a string value. Each string has a | and the portion in front of the | is a filepath. I want to replace that portion of the string with the correct filepath if it doesn't already match. What is the best way to go about doing this? Currently I use:
UPDATE content_history
SET doc_filename = replace (doc_filename, 'path that needs to be replaced', 'new path')
WHERE doc_filename LIKE 'old path%'
But if I don't have the exact path it doesn't replace so I have to run a select * query and manually go through and input all the different paths that are incorrect. It's not a viable long-term solution
Ideally you wouldn't store multiple values as delimited values in a single value, you should have a separate column for each distinct value, then you wouldn't be asking such a question.
You can use stuff:
set doc_filename=Stuff(doc_filename, 1, CharIndex('|', doc_filename)-1, 'new path')
you need to split value to avoid an incorrect update
update CH
set CH.doc_filename = 'new_path' + '|' + P.right_part
from content_history CH
outer apply
(
select left(CH.doc_filename, charindex('|', CH.doc_filename) - 1) as left_part
,right(CH.doc_filename, len(CH.doc_filename) - charindex('|', CH.doc_filename)) as right_part
where charindex('|', CH.doc_filename) != 0
) P
where P.left_part = 'old_path'

SQL: How to make a replace on the field ''

I have a very but tricky question for you guys. So, listen I have a field with spaces and numbers in one of my table columns. The key part is transform the content in a decimal field. The drawback is basically that for some rows I could get something like:
' 1584.00 '
' 156546'
'545.00 '
' '
So, to clean up my column, I have done a LTRIM and RTRIM so spaces gone. So now for a couple of records where the record were just spaces the new content is ''. Finally I need to convert this result to a decimal.
Issue: The thing is that for field that contend just the spaces the new result is '' and I'm not able to apply a REPLACE on this because it's a blank and the code below doesn't work:
SELECT REPLACE('','','0')
-- Final current verison
SELECT CAST(COALESCE(REPLACE(REPLACE([Gross_Weight],' ','0'),',',''),'0') AS DECIMAL(13,3))
How could I figure it out?
thanks so much
SELECT COALESCE(NULLIF(MyColumn, ''), 0)
This has the side-effect that you will also turn NULL values into 0, which you might not want. If that's a problem then a simple CASE statement should do the trick:
SELECT CASE WHEN MyColumn = '' THEN 0 ELSE CAST(MyColumn AS DECIMAL(10, 4)) END
Obviously you'll also have to incorporate any other manipulations that you're already doing.
No need for replace, just concatenate a zero to your column, like
SELECT RTRIM('0' + LTRIM(column))
I presume your data is in a table.
Lets call this table 'DATA' and the column 'VALUE'
Then you might use the below query
UPDATE DATA SET VALUE = 0 where VALUE = ''
To select the value do the below
select case ltrim(rtrim([Gross_Weight])) when ''
THEN 0
ELSE ltrim(rtrim([Gross_Weight])) END
Let me know if i get the requirement wrong.

SQL INSERT INTO statement - how to insert space when field is an empty string?

I have an INSERT INTO statement that I need to check if one of the field values I'm inserting is an empty string or not. If it is, I need to insert an actual SPACE instead of an empty string.
INSERT INTO Vendors (LegacyID, ExternalID1, ExternalID2, EIN, LegalName, DBAName, ...)
How would I determine if EIN is an empty string here ('') and if so, actually insert a space (' ')?
The same for an UPDATE statement
Update Vendors SET LegacyID = ds.LegacyID, ExternalID1 = ds.ExtID1, ExternalID2 = ds.ExtID2, ...)
Any help and examples would be greatly appreciated. Thank you.
You didn't include the VALUES portion of the INSERT, nor the EIN in your UPDATE, so you've omitted the sections where you'd actually be making changes.
Because of this, I could only take a best-guess shot at what your actual fields may be, but the general jist of the answer is to use a CASE statement around the value going to be inserted.
Example:
-- If field is '', then use ' '.
-- Otherwise, use it as-is.
CASE field WHEN '' THEN ' ' ELSE field END
Potential use-case (field names assumed):
INSERT INTO Vendors (EIN, ds.LegacyID, ...) VALUES (CASE ds.EIN WHEN '' THEN ' ' ELSE ds.EIN END, ds.LegacyID, ...)
UPDATE Vendors SET EIN = CASE ds.EIN WHEN '' THEN ' ' ELSE ds.EIN END
You could use IIF on all the values.
I am not sure which are the varchar values so I am going to take a guess. Also I have no idea how you are getting your values so I will assume hard coded for now.
INSERT INTO Vendors (LegacyID, ExternalID1, ExternalID2, EIN, LegalName, DBAName, ...)
VALUES (LegacyID, ExternalID1, ExternalID2, EIN, IIF(LegalName = '', ' ', LegalName), IIF(DBAName = '', ' ', DBAName), ...)
-- or
Update Vendors SET LegacyID = ds.LegacyID
, ExternalID1 = ds.ExtID1
, ExternalID2 = ds.ExtID2
, LegalName = IIF(ds.LegalName = '', ' ', ds.LegalName)
, DBAName = IIF(ds.DBAName = '', ' ', ds.LegalName)
...
Also I hope you have a valid reason/business case for doing this. If you really want an empty value the best thing to use is an empty string and for no value use null. Persisting a space only seems like an odd requirement, probably something that is probably only needed in the presentation layer but should probably not make it down into the persistence store.

T-SQL Split String Like Clause

I have declare #a varchar(100) = 'abc bcd cde def'. What I need is to select from a table where a column is like 'abc' or 'bcd' or 'cde' or 'def'. I can use a split function and a while to get what I want, but somewhere I saw a smart solution using replace or something similar and I just can't remember it.
I know I can use an xml variable, and parse it that way. However, the value is part of a large procedure, and the best way for me is to use it in string form.
I know I can solve this by building a dynamic sql query, but that is not an option in the domain I'm working in.
Damn, I just can remember the solution. Its a hack, a little dirty trick that do the job.
Anyways, I ll use the code bellow (Im over SQL Server 2008), is it a good idea? I prefer it over the dirty split. Is it more performatic?
declare #w varchar(100) = 'some word'
declare #f xml
set #f = '<word>' + replace(#w, ' ', '</word><word>') + '</word>'
select
template.item.value('.', 'varchar(100)') as word
from #f.nodes('/word') template(item)
Use a function to split the individual items into a table, one record per item. Then you simply join to that table.
insert into #FilterTable (filters)
select Items from dbo.Split(#YourFilterString)
select *
from YourTable yt
join #FilterTable f on f.filters = yt.YourColumn
Of course my example is using equality. It gets more complicated if you truly intend to use "like" with wildcards.
In tsql you can use a pattern col like '[abcd]'
http://msdn.microsoft.com/en-us/library/ms179859.aspx
For matching multiple words (not letter) and without dynamic SQL, you'll have to get the values into a temp table. For a split function try this page http://www.sommarskog.se/arrays-in-sql-2005.html#iterative and look at the List of Strings function iter_charlist_to_table.
Or maybe you are thinking of this little trick Parameterize an SQL IN clause from the SO CEO.
for 4 sections max
WHERE
PARSENAME(REPLACE(#a, ' ', '.'), 1) = 'xxx'
OR
PARSENAME(REPLACE(#a, ' ', '.'), 2) = 'xxx'
OR
PARSENAME(REPLACE(#a, ' ', '.'), 3) = 'xxx'
OR
PARSENAME(REPLACE(#a, ' ', '.'), 4) = 'xxx'

SQL Server 2005- Add area code to records shorter than 10 characters

Can anyone come up with a SQL routine or ideas to systematically append an area code to the beginning of every field in our SQL Server 2005 database that does not have an area code in it?
Perhaps someone could tell us how to return only rows that are less than 10 characters long and how to append the 3 digit area code to the beginning of each field string?
Thanks!
DECLARE #AreaCode char(3)
SET #AreaCode = 'XXX'
UPDATE myTable
SET myField = #AreaCode + myField
WHERE LEN(myField) < 10
AND myField NOT LIKE #AreaCode + '%'
This will work with SQL Server.
Ideally, the area code would be a separate column in your database. Since it's not designed that way though:
UPDATE
PhoneNumbers
SET
phone_number = '123' + phone_number
WHERE
LEN(phone_number) = 7
Of course, if people have formatted the phone numbers then this won't work. I would need to know more about the data that's in your table. You might have to do something like:
UPDATE
PhoneNumbers
SET
phone_number = '(123) ' + phone_number
WHERE
LEN(REPLACE(REPLACE(REPLACE(REPLACE(phone_number, '-', ''), '(', ''), ')', ''), '.', '') = 7
If people typed in stuff like "ext. 7" then that would further complicate things. See why it's better to break out a phone number instead of just having one column? ;)