Handling foreign key with no value

  • i have a database that links a laptop type in a user table to another table (laptop) on laptopid.

    however as a laptop is not always required, it then passes this in as an 'empty' value (no laptop type) and throws an error against the product table which has values of 1 2 or 3

    how would i best cater for this instance?

  • most foreign key constraints are placed in a column that allows NULL, which is undefined;

    if you are storing 'empty' or an empty string or anything else that's not in the FK lookup table, you get the error you are receiving.

    I've seen situations where a FK of 0/ 'Not Defined' was explicitly placed in the lookup table, so something is displayed by default, but that's more of a personal preference thing; I prefer nulls, and to validate the input to place null if no value was found from the application.

    Lowell


    --help us help you! If you post a question, make sure you include a CREATE TABLE... statement and INSERT INTO... statement into that table to give the volunteers here representative data. with your description of the problem, we can provide a tested, verifiable solution to your question! asking the question the right way gets you a tested answer the fastest way possible!

  • I'd like to echo Lowell's preference for NULLs in foreign keys instead of a zero. Of course, this means that you're going to have to outer join the tables if you want rows from both tables to always be returned. Placing a zero allows an inner join, but then you have to have a zero value in your parent table.

    If you have a procedure to populate the row, you could use this type of approach to make sure if an empty string is passed, you create the row using a NULL instead.

    DECLARE @x varchar(32);

    SET @x = 'b';

    SELECT CASE WHEN ISNULL(@x, '') = '' THEN NULL ELSE @x END;

    Since I don't have your table definitions, I used the variable @x to simulate the passed value. All we're really interested in here is the CASE statement. The others are just so it'll run as posted.

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply