Foreign key twice in same table for different columns in SQL server 2019

AHSAN ALI 101 Reputation points
2023-10-12T11:24:02.16+00:00

how can i create fk relation with user in order table with these columns

AcceptedBy

RejectedBy

User's image

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
14,494 questions
{count} votes

Accepted answer
  1. Erland Sommarskog 120.2K Reputation points MVP
    2023-10-12T21:18:58.4933333+00:00

    As Olaf suggests, it's straightforward:

    CREATE TABLE users (id int NOT NULL,
                        username nvarchar(100) NOT NULL,
                        role     nvarchar(100) NULL,
                        CONSTRAINT pk_users PRIMARY KEY (id)
    )
    
    CREATE TABLE orders (ordernumber int NOT NULL,
                        AcceptedBy   int  NULL,
                        RejectedBy   int  NULL,
                        CONSTRAINT pk_orders PRIMARY KEY (ordernumber),
                        CONSTRAINT fk_orders_users_AccepteBy 
                            FOREIGN KEY (AcceptedBy) REFERENCES users(id),
                        CONSTRAINT fk_orders_users_RejecteddBy 
                            FOREIGN KEY (RejectedBy) REFERENCES users(id)
    )
    go
    DROP TABLE orders, users
    
    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Olaf Helper 46,546 Reputation points
    2023-10-12T11:46:00.99+00:00

    Sure you can, why not?

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.