I want to update the entire email column using row index + email@gmail.com formate.
This is how the data in my table
id | |
---|---|
12 | abc@gmail.com |
23 | pqr@gmail.com |
This is the output that I want
id | |
---|---|
12 | 1email@gmail.com |
23 | 2email@gmail.com |
I tried the below query but it did not give my expected output.
;with C as
(
select email,row_number() over(order by id asc) as rowid
from cus
)
update C
set email = rowid+'email@gmail.com'
This is not only 3 rows there are more than 500 rows in my cus
table. It is better if someone can give a solution to me without looping. Please help me to create a SQL query for this. Thank you.
Maybe this is what you're aiming to do:
WITH C AS
(
SELECT email,ROW_NUMBER() OVER(ORDER BY id ASC) AS rowid
FROM cus
)
UPDATE cus
JOIN C
ON cus.email=C.email
SET cus.email=CONCAT(rowid,'email@gmail.com');
Join the table you want to update ( cus
) with cte
of C
then do the update accordingly.
@QisM have raised a concern over this syntax when the email
is not unique and since OP didn't mention, I agree that this is not the solution if the email
indeed is not unique. Due to that, I've made a slight modification to the syntax:
WITH C AS
(
SELECT id, email, ROW_NUMBER() OVER(ORDER BY id ASC) AS rowid
FROM cus
)
UPDATE cus
JOIN C
ON cus.id=C.id AND cus.email=C.email
SET cus.email=CONCAT(rowid,'email@gmail.com');
Now the cte
is with id
and the JOIN C ON..
condition I've added the checking of matching id
. Upon testing, this should fix the issue if e-mail is not unique .
this seems to work, but i'm sure there is a more elegant solution without the join...
SELECT * FROM cus ;
update
cus inner join
(
select id ,email,row_number() over(order by id asc) as rowid
from cus
)a
on a.id = cus.id
set cus.email = concat(a.rowid, a.email)
;
SELECT * FROM cus ;
complete test
-- create
CREATE TABLE cus (
id INTEGER PRIMARY KEY,
email TEXT NOT NULL
);
-- insert
INSERT INTO cus VALUES (0021, 'Clark');
INSERT INTO cus VALUES (0402, 'Dave');
INSERT INTO cus VALUES (005, 'Ava' );
SELECT * FROM cus ;
update
cus inner join
(
select id ,email,row_number() over(order by id asc) as rowid
from cus
)a
on a.id = cus.id
set cus.email = concat(a.rowid, a.email)
;
SELECT * FROM cus ;
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.