0

我有两个表,都已经填充了数据,并且包含以下列:


1 jobType char
jobDesc varchar

New_table jobID
int
jobType char

我想Table1.jobType用一jobID列替换,这样 Table1 现在将引用New_tableusing jobID。中的任何现有数据都Table1.jobType必须“翻译”为适当的jobID.

4

2 回答 2

1

The basic drill:

  • Start with the original job table

    create table dbo.job
    (
      id              int          not null identity(1,1) ,
      job_type        varchar(64)  not null ,
      job_description varchar(128) not null ,
    
      constraint job_PK primary key clustered (id) ,
    
    )
    
  • Create the new job type table (don't forget to populate it)

    create table dbo.job_type
    (
      id   int         not null identity(1,1) ,
      name varchar(64) not null ,
    
      constraint job_type_PK   primary key clustered ( id   ) ,
      constraint job_type_AK01 unique nonclustered   ( name ) ,
    
    )
    
  • Alter the table dbo.job to add a new job_type_id column

    alter table dbo.job
    add job_type_id int null
    
  • Update the job table, mapping the value of job_type_id based on the [old] job_type column's value.

    update dbo.job
    set job_type_id = jt.id
    from dbo.job      j
    join dbo.job_type jt on jt.name = j.job_type 
    
  • Alter the new column to make it non-nullable. This will fail until you've ensured that all rows have a non-null value for job_type_id:

    alter table dbo.job
    alter column job_type_id int not null
    
  • Add the new foreign key constraint needed

    alter table dbo.job
    add constraint job_AK01
    foreign key ( job_type_id )
    references dbo.job_type ( id )
    
  • The last and irrevocable step is to drop the old column. This will break any queries, stored procedures, etc. that reference this column...but you already did your homework in this department and have coordinated all necessary changes, right?

    alter table dbo.job drop column job_type
    
于 2012-09-26T19:14:22.197 回答
0

如果 Table1 中 JobType 列的数据都是以文本形式存储的 Integer 值,则运行以下命令:

ALTER TABLE Table1 ALTER COLUMN JobType INT

如果列包含非整数值,例如 ABC1、ABC2,那么您首先需要更改列中的数据。使用我在这里使用的示例值,您将运行:

UPDATE Table1
SET JobType = SUBSTRING(JobType,4,1)

然后你可以运行上面的 ALTER TABLE 语句

于 2012-09-26T18:55:04.480 回答