我看过类似于我需要的帖子,但它们都略显短暂。我也不确定我能做什么。如果无法完成,那么任何建议都将不胜感激。
我正在重建我的数据库,需要将三个不同表的部分合并为一个。目前我有三种不同类型的任务,我们称之为 DailyTasks ,评论和请求。所有三个表都有类似的字段,例如 DateCreated , DateCompleted , EstimatedHours 等。我创建了一个父表,名为 Tasks ,其中包含这些公共字段,其他表( DailyTasks ,评论和请求)仅包含特定于自身的字段。子表现在还有一个外键, TaskID ,它指向父表。我相信这是标准的数据库实践,如果我错了,请纠正我。
目前我在测试数据库中工作,因此我可以从实时数据库中提取原始数据以进行测试。我需要能够从每个表中提取公共字段并将它们放在父表中,同时将新主键放入子表的 TaskID 列。
我希望使用加入,但我不相信我可以在检索主键时以这种方式插入两个表。我的下一个想法是,如果一个联接不起作用就是使用游标。任何帮助将不胜感激,我希望我已经正确地解释了一切。
EDIT 这是表格的字段
TASKS (家长)
DailyTasks (儿童)
请求(儿童)
评论(儿童)
答案 0 :(得分:0)
Assuming you have a real hierarchy and thus every parent only has a single child record you could create a class like inheritance structure. With this setup you can ease things by making your PK also your foreign key to the parent table. This works nice with e.g. Entity Framework but its also simple to use when you query directly with TSQL.
Simplified the creation of the tables would look like. The parent table obviously does exist already just for completeness of the sample script):
CREATE TABLE [dbo].[Tasks] (
[Id] [uniqueidentifier] NOT NULL,
[CreatedBy] [nvarchar](150) NOT NULL,
[OtherColumns] [datetime] NOT NULL,
CONSTRAINT [PK_Tasks] PRIMARY KEY CLUSTERED ( [Id] ASC )
)
CREATE TABLE [dbo].[DailyTasks] (
[Id] [uniqueidentifier] NOT NULL,
[OtherColumns] [nvarchar](500) NULL,
CONSTRAINT [PK_DailyTasks] PRIMARY KEY CLUSTERED ( [Id] ASC )
)
ALTER TABLE [dbo].[DailyTasks]
ADD CONSTRAINT [FK_DailyTasks_Tasks] FOREIGN KEY([Id])
REFERENCES [dbo].[DailyTasks] ([Id])
With this setup you can easy do 3 inserts from your the parent table to the child tables and when you're done, drop the columns from the parent table. Something like this:
INSERT INTO [dbo].[DailyTasks]
([Id], [OtherColumns])
SELECT [Id], [OtherColumns]
FROM [dbo].[Tasks]