Programing

SQL Server에서 외래 키를 어떻게 만듭니 까?

lottogame 2020. 4. 11. 09:40
반응형

SQL Server에서 외래 키를 어떻게 만듭니 까?


SQL Server에 대한 "손으로 코딩 된"개체 생성 코드는 없었으며 외래 키 제거는 SQL Server와 Postgres에서 다르게 보입니다. 지금까지 내 SQL은 다음과 같습니다.

drop table exams;
drop table question_bank;
drop table anwser_bank;

create table exams
(
    exam_id uniqueidentifier primary key,
    exam_name varchar(50),
);
create table question_bank
(
    question_id uniqueidentifier primary key,
    question_exam_id uniqueidentifier not null,
    question_text varchar(1024) not null,
    question_point_value decimal,
    constraint question_exam_id foreign key references exams(exam_id)
);
create table anwser_bank
(
    anwser_id           uniqueidentifier primary key,
    anwser_question_id  uniqueidentifier,
    anwser_text         varchar(1024),
    anwser_is_correct   bit
);

쿼리를 실행할 때이 오류가 발생합니다.

메시지 8139, 수준 16, 상태 0, 줄 9 외래 키의 참조 열 수는 'question_bank'테이블의 참조 열 수와 다릅니다.

당신은 오류를 발견 할 수 있습니까?


create table question_bank
(
    question_id uniqueidentifier primary key,
    question_exam_id uniqueidentifier not null,
    question_text varchar(1024) not null,
    question_point_value decimal,
    constraint fk_questionbank_exams foreign key (question_exam_id) references exams (exam_id)
);

제약 조건을 자체적으로 만들려면 ALTER TABLE을 사용할 수 있습니다

alter table MyTable
add constraint MyTable_MyColumn_FK FOREIGN KEY ( MyColumn ) references MyOtherTable(PKColumn)

필자는 자체 제약 조건의 이름을 지정하기 때문에 Sara Chipps가 인라인 생성을 위해 언급 한 구문을 권장하지 않습니다.


다음을 사용하여 외래 키 제약 조건의 이름을 지정할 수도 있습니다.

CONSTRAINT your_name_here FOREIGN KEY (question_exam_id) REFERENCES EXAMS (exam_id)

AlexCuse의 답변이 마음에 들지만 외래 키 제약 조건을 추가 할 때마다주의해야 할 점은 참조 된 테이블의 행에서 참조 된 열에 대한 업데이트를 처리하는 방법, 특히 참조 된 행의 삭제를 원하는 방법입니다 처리 할 테이블.

다음과 같이 구속 조건이 작성되면 :

alter table MyTable
add constraint MyTable_MyColumn_FK FOREIGN KEY ( MyColumn ) 
references MyOtherTable(PKColumn)

.. 다음 참조하는 테이블의 해당 행이있는 경우 참조 된 테이블에서 업데이트 또는 삭제가 오류와 함께 날려 버리겠다.

그것은 당신이 원하는 행동 일지 모르지만, 내 경험상 훨씬 일반적이지 않습니다.

대신 다음과 같이 작성하십시오.

alter table MyTable
add constraint MyTable_MyColumn_FK FOREIGN KEY ( MyColumn ) 
references MyOtherTable(PKColumn)
on update cascade 
on delete cascade

.. 그런 다음 부모 테이블에서 업데이트 및 삭제하면 참조 테이블의 해당 행이 업데이트 및 삭제됩니다.

(나는 기본값이 변경되어야한다고 제안하는 것이 아니며, 기본값은주의를 기울이는 것이 좋습니다. 나는 단지 제약 만들고있는 사람 이 항상주의를 기울여야한다고 말하고 있습니다 .)

이것은 다음과 같이 테이블을 만들 때 수행 할 수 있습니다.

create table ProductCategories (
  Id           int identity primary key,
  ProductId    int references Products(Id)
               on update cascade on delete cascade
  CategoryId   int references Categories(Id) 
               on update cascade on delete cascade
)

create table question_bank
(
    question_id uniqueidentifier primary key,
    question_exam_id uniqueidentifier not null constraint fk_exam_id foreign key references exams(exam_id),
    question_text varchar(1024) not null,
    question_point_value decimal
);

-그것도 작동합니다. 아마도 좀 더 직관적 인 구조일까요?


쿼리를 사용하여 두 개의 테이블 열을 관계로 만들려면 다음을 시도하십시오.

Alter table Foreign_Key_Table_name add constraint 
Foreign_Key_Table_name_Columnname_FK
Foreign Key (Column_name) references 
Another_Table_name(Another_Table_Column_name)

테이블에서 외래 키를 만들려면

ALTER TABLE [SCHEMA].[TABLENAME] ADD FOREIGN KEY (COLUMNNAME) REFERENCES [TABLENAME](COLUMNNAME)
EXAMPLE
ALTER TABLE [dbo].[UserMaster] ADD FOREIGN KEY (City_Id) REFERENCES [dbo].[CityMaster](City_Id)

당신처럼, 나는 보통 수동으로 외래 키를 만들지 않지만 어떤 이유로 스크립트를 작성 해야하는 경우 일반적으로 ms sql server management studio를 사용하여 스크립트를 만들고 저장하고 변경하기 전에 Table Designer | 변경 스크립트 생성


이 스크립트는 외래 키로 테이블을 생성하는 것에 관한 것이며 참조 무결성 제약 조건 sql-server를 추가했습니다 .

create table exams
(  
    exam_id int primary key,
    exam_name varchar(50),
);

create table question_bank 
(
    question_id int primary key,
    question_exam_id int not null,
    question_text varchar(1024) not null,
    question_point_value decimal,
    constraint question_exam_id_fk
       foreign key references exams(exam_id)
               ON DELETE CASCADE
);

괴롭힘.
실제로, 이것을 올바르게하는 것은 조금 까다 롭습니다.

먼저 외래 키를 설정하려는 열에 기본 키가 있는지 확인해야합니다.

이 예에서는 dbo.T_SYS_Language_Forms.LANG_UID를 참조하여 테이블 T_ZO_SYS_Language_Forms에 외래 키가 작성됩니다.

-- First, chech if the table exists...
IF 0 < (
    SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES 
    WHERE TABLE_TYPE = 'BASE TABLE'
    AND TABLE_SCHEMA = 'dbo'
    AND TABLE_NAME = 'T_SYS_Language_Forms'
)
BEGIN
    -- Check for NULL values in the primary-key column
    IF 0 = (SELECT COUNT(*) FROM T_SYS_Language_Forms WHERE LANG_UID IS NULL)
    BEGIN
        ALTER TABLE T_SYS_Language_Forms ALTER COLUMN LANG_UID uniqueidentifier NOT NULL 

        -- No, don't drop, FK references might already exist...
        -- Drop PK if exists 
        -- ALTER TABLE T_SYS_Language_Forms DROP CONSTRAINT pk_constraint_name 
        --DECLARE @pkDropCommand nvarchar(1000) 
        --SET @pkDropCommand = N'ALTER TABLE T_SYS_Language_Forms DROP CONSTRAINT ' + QUOTENAME((SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
        --WHERE CONSTRAINT_TYPE = 'PRIMARY KEY' 
        --AND TABLE_SCHEMA = 'dbo' 
        --AND TABLE_NAME = 'T_SYS_Language_Forms' 
        ----AND CONSTRAINT_NAME = 'PK_T_SYS_Language_Forms' 
        --))
        ---- PRINT @pkDropCommand 
        --EXECUTE(@pkDropCommand) 

        -- Instead do
        -- EXEC sp_rename 'dbo.T_SYS_Language_Forms.PK_T_SYS_Language_Forms1234565', 'PK_T_SYS_Language_Forms';


        -- Check if they keys are unique (it is very possible they might not be) 
        IF 1 >= (SELECT TOP 1 COUNT(*) AS cnt FROM T_SYS_Language_Forms GROUP BY LANG_UID ORDER BY cnt DESC)
        BEGIN

            -- If no Primary key for this table
            IF 0 =  
            (
                SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
                WHERE CONSTRAINT_TYPE = 'PRIMARY KEY' 
                AND TABLE_SCHEMA = 'dbo' 
                AND TABLE_NAME = 'T_SYS_Language_Forms' 
                -- AND CONSTRAINT_NAME = 'PK_T_SYS_Language_Forms' 
            )
                ALTER TABLE T_SYS_Language_Forms ADD CONSTRAINT PK_T_SYS_Language_Forms PRIMARY KEY CLUSTERED (LANG_UID ASC)
            ;

            -- Adding foreign key
            IF 0 = (SELECT COUNT(*) FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS WHERE CONSTRAINT_NAME = 'FK_T_ZO_SYS_Language_Forms_T_SYS_Language_Forms') 
                ALTER TABLE T_ZO_SYS_Language_Forms WITH NOCHECK ADD CONSTRAINT FK_T_ZO_SYS_Language_Forms_T_SYS_Language_Forms FOREIGN KEY(ZOLANG_LANG_UID) REFERENCES T_SYS_Language_Forms(LANG_UID); 
        END -- End uniqueness check
        ELSE
            PRINT 'FSCK, this column has duplicate keys, and can thus not be changed to primary key...' 
    END -- End NULL check
    ELSE
        PRINT 'FSCK, need to figure out how to update NULL value(s)...' 
END 

항상이 구문을 사용하여 2 개의 테이블간에 외래 키 제약 조건을 만듭니다.

Alter Table ForeignKeyTable
Add constraint `ForeignKeyTable_ForeignKeyColumn_FK`
`Foreign key (ForeignKeyColumn)` references `PrimaryKeyTable (PrimaryKeyColumn)`

Alter Table tblEmployee
Add constraint tblEmployee_DepartmentID_FK
foreign key (DepartmentID) references tblDepartment (ID)

참고 URL : https://stackoverflow.com/questions/48772/how-do-i-create-a-foreign-key-in-sql-server

반응형