How to update text using "regular expressions" in SQL Server? - sql

In a column in a SQL Server database table, the value has a format of X=****;Y=****;Z=5****, where the asterisks represent strings of any lengths and of any values. What I need to do is to change that 5 to a 4 and keep the rest of the string unchanged.
Is there a way to use something like regular expressions to achieve what I want to do? If not using regular expressions, can it be done at all?

MS SQL sadly doesn't have any built in regex support (although it can be added via CLR) but if the format is fixed so that the part you want to change isZ=5toZ=4then usingREPLACEshould work:
REPLACE(your_string,'Z=5','Z=4')
For example:
declare #t table (str varchar(max))
insert #t values
('X=****;Y=****;Z=5****'),
('X=****;Y=**df**;Z=3**sdf**'),
('X=11**;Y=**sdfdf**;Z=5**')
update #t
set str = replace(str,'Z=5','Z=4')
-- or a slightly more ANSI compliant and portable way
update #t
set str = SUBSTRING(str,0, CHARINDEX('Z=5', str)) + 'Z=4' + SUBSTRING(str, CHARINDEX('Z=5', str)+3,LEN(str))
select * from #t
str:
X=****;Y=****;Z=4****
X=****;Y=**df**;Z=3**sdf**
X=11**;Y=**sdfdf**;Z=4**

We need more information. Under what circumstances should 5 be replaced by 4? If it's just where it occurs as the first character after the Z=, then you could simply do...
set Col = Replace(Col,'Z=5','Z=4')
Or, do you just want to replace 5 with 4 anywhere in the column value. In which case you'd obviously just do...
set Col = Replace(Col,'5','4')
Or possibly you mean that 5's should be replaced by 4's anywhere within the value after Z= which would be a lot harder.

update Table set Field = replace(Field, ';Z=5', ';Z=4')
And let's hope that your asterisked data doesn't contain semicolons and equality signs...

Related

How to extract numeric values from a column in SQL

I am trying to extract only the numeric values from a column that contains cells that are exclusively numbers, and cells that are exclusively letter values, so that I can multiply the column with another that contains only numeric values. I have tried
SELECT trim(INTENT_VOLUME)
from A
WHERE ISNUMERIC(INTENTVOLUME)
and also
SELECT trim(INTENT_VOLUME)
from A
WHERE ISNUMERIC(INTENTVOLUME) = 1
and neither works. I get the error Function ISNUMERIC(VARCHAR) does not exist. Can someone advise? Thank you!
It highly depends on DBMS.
in SqlServer you have a limited built-in features to do it, so the next query may not work with all variants of your data:
select CAST(INTENT_VOLUME AS DECIMAL(10, 4))
from A
where INTENT_VOLUME LIKE '%[0-9.-]%'
and INTENT_VOLUME NOT LIKE '%[^0-9.-]%';
In Oracle you can use regex in a normal way:
select to_number(INTENT_VOLUME)
from A
where REGEXP_LIKE(INTENT_VOLUME,'^[-+]?[0-9]+(\.[0-9]+)?$');
MySQL DBMS has also built-in regex
Try this, which tests if that text value can be cast as numeric...
select intent_volume
from a
where (intent_volume ~ '^([0-9]+[.]?[0-9]*|[.][0-9]+)$') = 't'

How to replace sql field case-sensitive value

I have one case-sensitive column.
How can I replace (Shpersonel,shPersonel, sHperSonel) to ShPersonel in all records?
my column Data is:
1- SHpersonel = 12 And Password= Ayuy122
2- ShpeRsonel = 10 And Password= jkjIUD122
3- ShPersonel = 08 And Password= Kjjam
...
You could use LOWER (or UPPER), which lots of DBMSes support, to look for a value case insensitively and update:
update your_table
set col = 'ShPersonel'
where lower(col) = 'shpersonel';
EDIT:
Further clarification explained that above data is stored in a single column - Which is not how it should be stored.
You should store the data in separate columns and then look for further normalization to remove unwanted dependencies.
UPDATE your_table
SET your_column = 'ShPersonel'
WHERE upper(your_column) = 'SHPERSONEL';
You didn't say what DBMS you're using. If it's SQL-Server, the following should work for you:
update MyTable
set TheData =
concat(
left(TheData,charindex('shpersonel',lower(t.TheData))-1),
'ShPersonel',
right(t.TheData,len(t.TheData) - charindex('shpersonel',lower(t.TheData)) - len('ShPersonel'))
)
from MyTable t
where
charindex('shpersonel',lower(t.TheData))>0
For other DBMS's you need to replace charindex with whatever that DBMS's equivalent may be. For example, Oracle and MySQL use InStr (which needs its arguments in the reverse order).

SQL Statement to UPDATE three characters in a string

How to take a string from a row in a column named 'link', and modify it by adding three letters to a specific index position in the string.
Specific example:
I want to select the value 'http://www.hello.no' and UPDATE it with 'http://www-x1.hello.no' using SQL statement(s).
Lets say the index position where '-x1' starts at will always be 10.
This needs to be accomplished using PostgreSQL. But if you can capture the logic with a generic SQL statement then great. :)
Postgresql has a function for doing replacements with patterns called regexp_replace. You can use that function like this:
UPDATE my_table
SET link = regexp_replace(link, 'www', 'www-x1')
WHERE <...>
Of course you could do it with the straight string manipulation, too:
UPDATE my_table
SET link = left(link, 10) || '-x1' || substring(link from 10)
WHERE <...>
This does what you ask for:
update the_table
set the_column = left(the_column, 10) || '-x1' || substring(the_column, 10);
however I'm not sure that this is what you want. It seems you want to insert the '-x1' in front of the first . which would be something different.

String input matched against a binary field in SQL WHERE

Here is the scenario:
I have a SQL select statement that returns a binary data object as a string. This cannot be changed it is outside the area of what I can modify.
So for example it would return '1628258DB0DD2F4D9D6BC0BF91D78652'.
If I manually add a 0x in front of this string in a query I will retrieve the results I'm looking for so for example:
SELECT a, b FROM mytable WHERE uuid = 0x1628258DB0DD2F4D9D6BC0BF91D78652
My result set is correct.
However I need to find a Microsoft SQL Server 2008 compatible means to do this programatically. Simply concatenating 0x to the string variable does not work. Obvious, but I did try it.
Help please :)
Thank you
Mark
My understanding of your question is that you have a column uuid, which is binary.
You are trying to select rows with a particular value in uuid, but you are trying to use a string like so:
SELECT a, b FROM mytable WHERE uuid = '0x1628258DB0DD2F4D9D6BC0BF91D78652'
which does not work. If this is correct, you can use the CONVERT function with a style of 2 to have SQL Server treat the string as hex and not require a '0x' as the first characters:
SELECT a, b
FROM mytable
WHERE uuid = CONVERT(binary(16), '1628258DB0DD2F4D9D6BC0BF91D78652', 2)

Regular expressions inside SQL Server

I have stored values in my database that look like 5XXXXXX, where X can be any digit. In other words, I need to match incoming SQL query strings like 5349878.
Does anyone have an idea how to do it?
I have different cases like XXXX7XX for example, so it has to be generic. I don't care about representing the pattern in a different way inside the SQL Server.
I'm working with c# in .NET.
You can write queries like this in SQL Server:
--each [0-9] matches a single digit, this would match 5xx
SELECT * FROM YourTable WHERE SomeField LIKE '5[0-9][0-9]'
stored value in DB is: 5XXXXXX [where x can be any digit]
You don't mention data types - if numeric, you'll likely have to use CAST/CONVERT to change the data type to [n]varchar.
Use:
WHERE CHARINDEX(column, '5') = 1
AND CHARINDEX(column, '.') = 0 --to stop decimals if needed
AND ISNUMERIC(column) = 1
References:
CHARINDEX
ISNUMERIC
i have also different cases like XXXX7XX for example, so it has to be generic.
Use:
WHERE PATINDEX('%7%', column) = 5
AND CHARINDEX(column, '.') = 0 --to stop decimals if needed
AND ISNUMERIC(column) = 1
References:
PATINDEX
Regex Support
SQL Server 2000+ supports regex, but the catch is you have to create the UDF function in CLR before you have the ability. There are numerous articles providing example code if you google them. Once you have that in place, you can use:
5\d{6} for your first example
\d{4}7\d{2} for your second example
For more info on regular expressions, I highly recommend this website.
Try this
select * from mytable
where p1 not like '%[^0-9]%' and substring(p1,1,1)='5'
Of course, you'll need to adjust the substring value, but the rest should work...
In order to match a digit, you can use [0-9].
So you could use 5[0-9][0-9][0-9][0-9][0-9][0-9] and [0-9][0-9][0-9][0-9]7[0-9][0-9][0-9]. I do this a lot for zip codes.
SQL Wildcards are enough for this purpose. Follow this link: http://www.w3schools.com/SQL/sql_wildcards.asp
you need to use a query like this:
select * from mytable where msisdn like '%7%'
or
select * from mytable where msisdn like '56655%'