1

Create statement for my first table: 'users':

CREATE TABLE users 
(
    uid INT NOT NULL IDENTITY PRIMARY KEY,
    firstName VARCHAR(50) NOT NULL,
    lastName VARCHAR(50) NOT NULL,
    middle VARCHAR(50) NOT NULL,
    ssn VARCHAR(12) NOT NULL,
    dob DATE NOT NULL,
    phone VARCHAR(10) NOT NULL,
    email VARCHAR(255) NOT NULL
)

Create statement for my second table: 'ds':

CREATE TABLE ds 
(
    dsu VARCHAR(50) NOT NULL,
    dsp VARCHAR(50) NOT NULL,
    dsImage VARCHAR(50) NOT NULL,
    dsid INT NOT NULL, 
    Name nvarchar(50),

    CONSTRAINT PK_dsid 
        PRIMARY KEY NONCLUSTERED (dsid),
    CONSTRAINT FK_users_uid 
        FOREIGN KEY (dsid) REFERENCES users (uid)
                ON DELETE CASCADE
                ON UPDATE CASCADE
);

The first table's uid column will auto-increment with each new row I insert. I want to setup the ds table's dsid column value in each new row to automatically update to match the users table uid column value.

When I try to INSERT INTO values into the ds table:

INSERT INTO ds (dsu, dsp, dsImage)
VALUES ('john.smith', '1234567', 'Tiger')

I get the following error:

Msg 515, Level 16, State 2, Line 1
Cannot insert the value NULL into column 'dsid', table 'company.dbo.ds'; column does not allow nulls. INSERT fails.

So, I'm trying to figure out if I'm setting up the primary key and foreign key create statements correctly to achieve the desired result, and also why I'm getting the error, and if I'm even approaching this task/problem correctly.

Any help is greatly appreciated, thank you!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 3
    `dsid INT NOT NULL` and `Cannot insert the value NULL into column 'dsid'` make a predictable pair. Typically you would either `insert` into `users` first and use `Scope_Identity()` or an `output` clause to capture the new `uid` value(s), then use the appropriate data when inserting into `ds`. If you are just inserting into `ds` then you would use a subquery or `join` with `users` to get the appropriate `uid` value(s). – HABO Aug 28 '20 at 03:14
  • 1
    This is not a good idea. – FLICKER Aug 28 '20 at 04:55

0 Answers0