在5个表之后,哪个主键是级别ID。在userlevel1表中,主键是Level1ID,UserLevel2表主键是Level2ID,它使用外键与UserLevel1表链接。相同结构用户级别3,级别4,级别5
CREATE TABLE [tdm].[UserLevel1](
[UserID] [int],
[Level1ID] [int] IDENTITY(1,1) NOT NULL,
[USerID] [int] NOT NULL,
[LevelName] [nvarchar](50) NOT NULL,
[GeoCode] [nvarchar](50) NULL,
[IsDeleted] [bit] NULL
)
CREATE TABLE [tdm].[UserLevel2](
[Level2ID] [int] IDENTITY(1,1) NOT NULL,
[Level1ID] [int] NOT NULL,
[LevelName] [nvarchar](50) NOT NULL,
[GeoCode] [nvarchar](50) NULL,
[IsDeleted] [bit] NULL
)
CREATE TABLE [tdm].[UserLevel3](
[Level3ID] [int] IDENTITY(1,1) NOT NULL,
[Level2ID] [int] NOT NULL,
[LevelName] [nvarchar](50) NOT NULL,
[GeoCode] [nvarchar](50) NULL,
[IsDeleted] [bit] NULL
)
CREATE TABLE [tdm].[UserLevel4](
[Level4ID] [int] IDENTITY(1,1) NOT NULL,
[Level3ID] [int] NOT NULL,
[LevelName] [nvarchar](50) NOT NULL,
[GeoCode] [nvarchar](50) NULL,
[IsDeleted] [bit] NULL
)
CREATE TABLE [tdm].[UserLevel5](
[Level5ID] [int] IDENTITY(1,1) NOT NULL,
[Level4ID] [int] NOT NULL,
[LevelName] [nvarchar](50) NOT NULL,
[GeoCode] [nvarchar](50) NULL,
[IsDeleted] [bit] NULL
)
对于上表的插入或更新,我已经为每个表使用了MERGE查询。以下代码包含3级表
MERGE INTO tdm.CustomerLevel3 AS [Target]
USING @TempCustomerLevel3 AS [Source]
ON [Source].LevelID = [Target].Level3ID
WHEN NOT MATCHED
AND [Source].[GeoCode]<>''
AND [Source].[LevelName]<>''
THEN
INSERT
(
[Level2ID]
,[LevelName]
,[GeoCode]
,[IsDeleted]
)
VALUES
(
[Source].[ParentLevelID]
,[Source].[LevelName]
,[Source].[GeoCode]
,[Source].[IsDeleted]
)
WHEN MATCHED
THEN
UPDATE SET
[Level2ID]=[Source].[ParentLevelID]
,[LevelName] = [Source].[LevelName]
,[GeographyCode] = [Source].[GeographyCode]
,[IsDeleted]=IIF([Source].[GeographyCode]<>'' AND [Source].[LevelName]<>'',[Source].[IsDeleted],1);
我为每个级别的表写了5个合并查询。级别1表和级别2可以管理因为它有UserID所以我可以加入表并获取父id值,但是对于插入时的其他表我没有当前我链接到其他表的级别id我通过插入表的重复值的GeoCode链接。