我想在我的数据中为特定列添加一个数字:但我的@id是静态的并且没有变化,我错过了什么 //那就是我需要的东西
names
-----
david1
david2
david3
//这是我的代码
DECLARE @var INT
SET @var = 0
update [dbo].[ContactBase]
set FirstName = 'david + convert(varchar(10),@var )
set @var =@var + 1;
答案 0 :(得分:1)
看看以下内容。
;
WITH CTE
AS (SELECT FirstName
, ROW_NUMBER() OVER (ORDER BY (SELECT 1
)) RN
FROM ContactBase
)
SELECT *
FROM CTE
;
WITH CTE
AS (SELECT FirstName
, ROW_NUMBER() OVER (ORDER BY (SELECT 1
)) RN
FROM ContactBase
)
UPDATE CTE
SET FirstName = FirstName + CAST(RN AS VARCHAR(10))
第一个调用只显示cte的输出,第二个实际处理更新。
同样使用行号选项,您还可以按名称分隔,以便非常简单地为您提供david1,david2,Jon1,Jon2等。是一种重复数据删除的便捷方式。
DECLARE @ContactBase AS TABLE (FirstName VARCHAR(10))
INSERT INTO @ContactBase
(FirstName)
VALUES ('David'),('David'),('David')
SELECT * FROM @ContactBase
;WITH CTE
AS (SELECT FirstName
, ROW_NUMBER() OVER (ORDER BY (SELECT 1
)) RN
FROM @ContactBase
)
UPDATE CTE
SET FirstName = FirstName + CAST(RN AS VARCHAR(10))
SELECT * FROM @ContactBase
答案 1 :(得分:0)
我不明白你想要什么...你想要
答案 2 :(得分:0)
使用ROW_NUMBER
生成数字。
update n
set firstname = 'david' + cast(num as varchar(10))
from
(select firstname, row_number() over (order by firstname) as num from dbo.contactbase) n;
REXTESTER演示:http://rextester.com/CZDJ47320