Table : Dots
CREATE TABLE dots
(
cola VARCHAR(50),
NAME VARCHAR(10),
);
Insertion :
INSERT INTO dots VALUES('59.96.12.563','');
INSERT INTO dots VALUES('594.966.127.5683','');
INSERT INTO dots VALUES('5998.8896.4412.22563','');
INSERT INTO dots VALUES('791','');
INSERT INTO dots VALUES('891','');
INSERT INTO dots VALUES('691','');
Note : Now I want to update the NAME
column in the table Dots
to the value IP
for those records who contains the 3 dots on it in column Cola
. For example as shown below in the expected result.
Result :
Cola NAME
--------------------------------
59.96.12.563 IP
594.966.127.5683 IP
5998.8896.4412.22563 IP
791
891
691
Try the below code snippet -
UPDATE dots SET Name = 'IP'
WHERE (LEN(cola) - LEN(REPLACE(cola, '.', ''))) / LEN('.') = 3
Try this:
UPDATE dots
SET NAME = 'IP'
WHERE cola LIKE '%.%.%.%'
The correct way of checking would be using LIKE , this will check for exactly 3 dots:
WHERE
cola like '%.%.%.%'
and cola not like '%.%.%.%.%'
If you fancy the REPLACE method. This is the correct syntax:
WHERE
LEN(REPLACE(cola, '.', '.X')) - LEN(cola) = 3
The reason is that
LEN(cola) - LEN(REPLACE(cola, '.', '')) = 3
Will fail in case the text ends with space period.
Example:
SELECT LEN(REPLACE('. .', '.', ''))
Returns 0 indication there are 4 dots in the text.
This may not be an issue since the spaces are probably not existing in your IP addresses.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.