How can I move data from one column of a parent into a new child table?

二次信任 提交于 2019-12-13 01:24:57

问题


I have two tables: WordForm and WordDefinition:

CREATE TABLE [dbo].[WordForm] (
    [WordFormId]    VARCHAR (20)  NOT NULL,
    [WordId]     VARCHAR (20)  NOT NULL,
    [Primary]    BIT           DEFAULT ((0)) NOT NULL,
    [PosId]      INT           NOT NULL,
    -- I want to move text data from this column into 
    -- the WordDefinition table column called Definition
    -- and then I will remove the column from here later.
    [Definition] VARCHAR (MAX) NULL, 
    [Sample]     VARCHAR (MAX) NULL,
    [Synonym]    VARCHAR (100) NULL,
    PRIMARY KEY CLUSTERED ([WordFormId] ASC),
    CONSTRAINT [FK_WordFormPos] FOREIGN KEY ([PosId]) REFERENCES [dbo].[Pos] ([PosId]),
    CONSTRAINT [FK_WordFormWord] FOREIGN KEY ([WordId]) REFERENCES [dbo].[Word] ([WordId])
);



CREATE TABLE [dbo].[WordDefinition]
(
    [WordDefinitionId] INT IDENTITY (1, 1) NOT NULL,
    [WordFormId]    VARCHAR (20)  NOT NULL,
    [Definition]  VARCHAR (MAX) NOT NULL
    CONSTRAINT [PK_WordDefinition] PRIMARY KEY CLUSTERED ([WordDefinitionId] ASC),
)

Initially the WordForm table was created to hold single definitions but now I realize there can be more definitions for each WordForm.

To implement this I added the WordDefinition table. One WordForm row to Many WordDefinition rows.

But now what I need to do is to go through the WordForm table and add an entry with the original definition (from WordForm) and copy this into the WordDefinition table for each row in WordForm.

Is this something I could do only with SQL or would I need to use a cursor. Any help and advice on how to do this would be much appreciated.


回答1:


I think you can just use 1 query INSERT INTO SELECT to do this, something like this:

INSERT INTO [dbo].[WordDefinition]
SELECT [WordFormId], [Definition] 
FROM [dbo].[WordForm]

After that you can delete the old column Definition from WordForm.



来源:https://stackoverflow.com/questions/36810385/how-can-i-move-data-from-one-column-of-a-parent-into-a-new-child-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!