我的表[ID]
中有一个标识列。我也有一个基于身份列的计算列,像这样;
create table [dbo].[tblMaster] (
ID bigint identity(1,1),
GlobalFamilyUniqueID int,
DupeIdentifier as cast('EDME' + RIGHT('00000000'+ISNULL(cast([ID] as nvarchar(max)),''),8) as nvarchar(30)),
ControlNumber nvarchar(30),
NuixGuid nvarchar(50),
TopLvlGuid nvarchar(50),
ParentGuid nvarchar(50),
CustodianArtifactID int,
IsGlobalFamilyUnique int,
IsCustodianFamilyUnique int,
IsItemUnique int,
ItemUniqueDupID nvarchar(100),
IsChild int,
GroupIdentifier nvarchar(100),
DatasourceID int,
MD5Hash nvarchar(32),
GlobalFamilyDupID nvarchar(100),
CustodianFamilyDupId nvarchar(100),
ExportSessionID nvarchar(100)
)
我想基于ControlNumber
列更新IsGlobalFamilyUnique
列。此刻,无论DupeIdentifier
是IsGlobalFamilUnique
还是1
,0
都会有一个值。我需要ControlNumber
具有一个基于ControlNumber
字段中的最后一个值的增量值(我创建了另一个名为GlobalFamilyUnqiueID
的列作为“计数器”列),但仅当{{1 }}是IsGlobalFamilUnique
。
这是我到目前为止的位置;
1
问题在于,再次运行代码时,update x
set
GlobalFamilyUniqueID = [ProposedGlobalFamilyUniqueID],
ControlNumber = [ProposedControlNumber]
from(
Select top 10 [id],
DupeIdentifier,
-- ControlNumber,
isglobalfamilyunique,
--GlobalFamilyUniqueID,
GlobalFamilyUniqueID,
Row_Number() Over(Order By [id]) [ProposedGlobalFamilyUniqueID],
ControlNumber,
'TEST' + RIGHT('00000000'+ISNULL(cast(Row_Number() Over(Order By [id]) as nvarchar(30)),''),8) [ProposedControlNumber]
From dbo.tblMaster mstr1
where IsGlobalFamilyUnique = 1 and ControlNumber is null
)x
将再次从ProposedGlobalFamilyUniqueID
开始。它应从1
中ProposedGlobalFamilyUniqueID
的最后一个值开始。我认为这是因为我将查询限制在dbo.tblMaster
的位置,但是我不知道该如何解决。
最终结果应为连续的ControlNumber is null
值,其中ControlNumber
示例数据
IsGlobalFamilyUnique = 1
答案 0 :(得分:0)
将ControlNumber字段保留为数字,请不要将其设置为varchar,因为它将无法计算。
首先,在尝试脚本之前,删除所有现有的控制编号值。
然后尝试这个:
DECLARE @max as bigint
SELECT @max = Max(id)
FROM tblMaster
Select [id],
DupeIdentifier,
-- ControlNumber,
isglobalfamilyunique,
--GlobalFamilyUniqueID,
GlobalFamilyUniqueID,
@max + Row_Number() Over(Order By [id]) [ProposedGlobalFamilyUniqueID],
ControlNumber
From dbo.tblMaster mstr1
where IsGlobalFamilyUnique = 1 and ControlNumber is null
update x
set
GlobalFamilyUniqueID = [ProposedGlobalFamilyUniqueID],
ControlNumber = x.Proposed_Control_Number
from(
Select [id],
DupeIdentifier,
-- ControlNumber,
isglobalfamilyunique,
--GlobalFamilyUniqueID,
GlobalFamilyUniqueID,
Row_Number() Over(Order By [id]) [ProposedGlobalFamilyUniqueID],
ControlNumber,
@max + Row_Number() Over(Order By [id]) as Proposed_Control_Number
From dbo.tblMaster mstr1
Where IsGlobalFamilyUnique = 1 and ControlNumber is null
)x