如何在MS SQL中引用计算列?

时间:2016-07-27 01:17:11

标签: sql-server

我写了一个查询如下。

create table registration(
    id int identity(1000,1) ,
    first_name varchar(45) unique,
    sur_name varchar(45),
    address_line1 varchar(45),
    address_line2 varchar(45),
    state varchar(45),
    city varchar(45),
    email_id varchar(45),
    contact_no varchar(45),
    date_of_birth date,
    apply_type varchar(45),
    qualification varchar(45),
    gender varchar(45),
    password as CONVERT(VARCHAR(4),DATEPART(dd,GETDATE())) +
        substring(CONVERT(VARCHAR(4),DATENAME(mm,GETDATE())),1,3) +
        convert(varchar(4),FLOOR(RAND(CHECKSUM(NEWID()))*(999-100)+100)),
    hint_question varchar(50),
    hint_answer varchar(50),
    user_id as substring(apply_type,1,4) + convert(char(45),id)                    
        persisted primary key not null);

create table passport(
    id int identity(1000,1),
    Passport_Number as substring(Booklet_type,1,2) +
        convert(varchar(100),id) persisted primary key not null,
    user_id varchar(200) constraint fk_uid foreign key(user_id) references
        registration(user_id) on delete cascade,
    Type_of_Passport varchar(45),
    Type_of_Service varchar(50),
    Booklet_type varchar(50),
    Address1 varchar(50),
    Address2 varchar(50),
    City varchar(50),
    State varchar(50),
    Country varchar(50)n
    Pin int,
    Number_of_Years int,
    Date_Of_Application date,
    Issue_Date date,
    Amount int,
    Reason_for_reissue varchar(50),
    Expired_Date date);

但我收到以下错误:

    Column 'registration.user_id' is not the same length or scale as referencing column 'passport.user_id' in foreign key 'fk_uid'. Columns participating in a foreign key relationship must be defined with the same length and scale.

如何纠正这个问题?

1 个答案:

答案 0 :(得分:3)

将注册中的user_id转换或转换为varchar(200),即与护照中的相同

user_id as CONVERT(VARCHAR(200), 
                    substring(apply_type,1,4) + 
                    convert(char(45),id) )                    
           persisted primary key not null);