表名:Citizen
Firstname Lastname Telephone1 Many other columns......
John Smith 03907625212
Andrew Evans 0807452132
Bill Towny 05907122139
Dame Beaut 07894650569
理想情况应如下所示:
Firstname Lastname Telephone1 Many other columns......
John Smith 01907000001
Andrew Evans 01907000002
Bill Towny 01907000003
Dame Beaut 01907000004
之前,有人能够使用select语句提供脚本。 Script for incrementally creating records
select [First Name],
[Last Name],
[All LP Surname],
[All Liable Partys PIN],
'01907' + RIGHT('00000' + CAST(ROW_NUMBER() OVER (ORDER BY [Last Name]) AS VARCHAR), 6) AS 'Telephone1',
[Telephone2],
[Mobilephone],
[EmailAddress]
FROM citizen
但是我想要实现更改,因为我只能使用上面的选择脚本来查看它们。
答案 0 :(得分:2)
这不需要JOIN
。您可以使用添加的新列的值直接从CTE
更新。我假设您希望将Telephone1
列设置为等于查询的计算Telephone1
列。这是以下代码:
;With ToUpdate As
(
Select *,
'01907' +
Right('00000' +
Cast(Row_Number() Over (Order By [Last Name]) As Varchar)
, 6)
As NewTelephone1
From Citizen
)
Update ToUpdate
Set Telephone1 = NewTelephone1
这会将您的citizen
表的Telephone1
列更新为计算出的NewTelephone1
的值。
答案 1 :(得分:1)
UPDATE c
SET c.[Telephone] = '0' + CAST(1907000000 + t.RowNumber AS VARCHAR)
FROM Citizen c
INNER JOIN
(
SELECT [First Name],
[Last Name],
ROW_NUMBER() OVER (ORDER BY [Last Name], [First Name]) AS RowNumber
FROM Citizen
) t
ON c.[First Name] = t.[First Name] AND
c.[Last Name] = t.[Last Name]
答案 2 :(得分:1)
您需要使用CTE作为窗口函数。像这样:
WITH cte AS
(
SELECT
[All Liable Partys PIN],
'01907' + RIGHT('00000' + CAST(ROW_NUMBER() OVER (ORDER BY [LastName]) AS VARCHAR), 6) AS 'NewTelephone1'
FROM
[citizen]
)
UPDATE
c
SET
c.[Telephone1] = cte.[NewTelephone1]
FROM
[citizen] c
JOIN cte
ON c.[All Liable Partys PIN] = cte.[All Liable Partys PIN]
我在这里假设我们可以使用PIN字段加入。