Help Automatically Populating Fields base on PK

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ITHELP85
    New Member
    • Nov 2008
    • 8

    Help Automatically Populating Fields base on PK

    using SQL Server 2005

    I have a table SALES_ITEM, users should be able to input the Primary Keys (ItemNumberSK and InvoiceNumber), and Qty. I want the ItemName and UnitPrice fields to update automatically from the WAREHOUSE table.
    I wrote a trigger already but something is wrong with it as I get this error (My code is listed under the error):

    ---------------------------
    Microsoft SQL Server Management Studio
    ---------------------------
    No row was updated.

    The data in row 1 was not committed.
    Error Source: .Net SqlClient Data Provider.
    Error Message: Cannot insert the value NULL into column 'InvoiceNumberS K', table 'prac.dbo.SALES _ITEM'; column does not allow nulls. INSERT fails.

    The statement has been terminated.

    Correct the errors and retry or press ESC to cancel the change(s).
    ---------------------------
    OK Help
    ---------------------------

    /* Creates SALES_ITEM table */

    CREATE TABLE SALES_ITEM(
    InvoiceNumberSK int NOT NULL,
    ItemNumberSK int NOT NULL,
    ItemName char(50) NULL,
    Qty numeric(7, 0) NOT NULL,
    UnitPrice money NULL,
    ExtendedPrice AS CASE
    WHEN UnitPrice > 0 AND Qty > 0 Then UnitPrice * Qty
    END

    CONSTRAINT Sales_ItemPK PRIMARY KEY (InvoiceNumberS K, ItemNumberSK),
    CONSTRAINT Sales_ItemInvoi ceNumberFK FOREIGN KEY (InvoiceNumberS K) REFERENCES SALES (InvoiceNumberS K),
    CONSTRAINT Sales_ItemItemN umberSKFK FOREIGN KEY (ItemNumberSK) REFERENCES WAREHOUSE (ItemNumberSK)
    );

    /* Creates WAREHOUSE table */

    CREATE TABLE WAREHOUSE(
    ItemNumberSK int NOT NULL,
    ItemName char(50) NULL,
    ItemUnitPrice money NULL,
    ItemQty numeric(7, 0) NULL,

    CONSTRAINT WarehousePK PRIMARY KEY (ItemNumberSK),
    CONSTRAINT WarehouseFK FOREIGN KEY (ItemNumberSK) REFERENCES ITEM_PURCHASE (ItemNumberSK)
    );




    /* Creates Trigger that Automatically Inserts ItemName & UnitPrice From WAREHOUSE table, with the matching ItemNumberSK */

    go
    CREATE TRIGGER Populate_ItemNa me_UnitPrice ON SALES_ITEM AFTER INSERT
    AS
    DECLARE
    @ItemNumberSK int,
    @ItemName char(50),
    @UnitPrice money


    SELECT @ItemNumberSK = ItemNumberSK
    FROM WAREHOUSE


    BEGIN
    INSERT INTO SALES_ITEM (ItemName, UnitPrice)
    VALUES (@ItemName, @UnitPrice)

    END
  • ck9663
    Recognized Expert Specialist
    • Jun 2007
    • 2878

    #2
    Removed unnecessary quote.

    You never store any value in @ItemName and @UnitPrice

    Code:
    	INSERT INTO SALES_ITEM (ItemName, UnitPrice)
    	VALUES (@ItemName, @UnitPrice)

    -- CK

    Comment

    Working...