我想用增量值更新一个表的名字和姓氏。例如: -
ID FirstName
1 Demo_01
2. Demo_02
3. Demo_03
4. And so on....
此表有1000条记录。但出于演示目的,我们不想共享真实姓名。那么请帮助如何使用“Demo_ +增量值减1”来更新名字?
答案 0 :(得分:8)
;with cte as
(
SELECT FirstName, ROW_NUMBER() OVER (ORDER BY ID) RN
FROM YourTable
)
UPDATE cte
SET FirstName = 'Demo_ ' + CAST(RN AS VARCHAR(10))
或者您的意思是您想直接使用ID字段吗?
UPDATE YourTable
SET FirstName = 'Demo_ ' + CAST(ID AS VARCHAR(10))
注意:您说您有数千条记录,但显然它们不适合Demo_01
格式。假设你想允许最多6个数字并使用前导零填充你可以使用类似的东西。
UPDATE YourTable
SET FirstName = 'Demo_ ' + RIGHT('000000' + CAST(ID AS VARCHAR(6)),6)
答案 1 :(得分:1)
没有CTE:
DECLARE @NewID INT;
SET @NewID = 0;
UPDATE myTable
SET @NewID = ID = @NewID + 1
UPDATE myTable
SET FirstName = 'Demo_ ' + RIGHT('000000' + CAST(ID AS VARCHAR(6)),6)
答案 2 :(得分:0)
对于MySQL
UPDATE tablename SET FirstName = CONCAT('Demo_',ID);