Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie
Hi there,
There is an issue with role permissions that is being worked on at the moment.
If you are having trouble with access or permissions on regional forums please post here to get access: https://www.boards.ie/discussion/2058365403/you-do-not-have-permission-for-that#latest

Tricky SQL Problem

  • 30-07-2008 10:29am
    #1
    Registered Users, Registered Users 2 Posts: 500 ✭✭✭


    Folks,

    I have a tricky one.

    A Customer table - with thousands of records. Fields - Cust_ID, Cust_Name.
    An Order Table I imported. It contains order details and a Customer_Name.

    I dont want the Customer_Name in Orders. I want Customer_ID. A FK relationship.

    I need to preform some lookup to replace the Customer_Name with the Cust_ID.

    Any help?


Comments

  • Registered Users, Registered Users 2 Posts: 68,317 ✭✭✭✭seamus


    What server?


  • Registered Users, Registered Users 2 Posts: 500 ✭✭✭warrenaldo


    SQL Server


  • Registered Users, Registered Users 2 Posts: 68,317 ✭✭✭✭seamus


    First thing I would do is add in an additional column for the customer ID, so you don't go overwriting the name and getting all mixed up.

    So
    ALTER TABLE [Order] ADD COLUMN [Customer_ID] INT NULL

    Then you do an update into this column based on the customer name:

    UPDATE Order
    SET [Order].[Customer_ID] = [Customer].[Customer_ID]
    FROM [Order], [Customer]
    WHERE
    [Order].[Customer_Name] = [Customer].[Customer_Name]

    The syntax might be a bit off, but it should work.

    Then you get the rows where there were no matches:

    SELECT * FROM [Order] WHERE [Customer_ID] IS NULL

    And hopefully there are only a few, so you can correct them manually.

    Then you drop the Customer_Name column from the order table, set the Cust_ID column to NOT NULL and create your FK constraint.


  • Registered Users, Registered Users 2 Posts: 500 ✭✭✭warrenaldo


    My god - its so handy when you put it like that - I was way over complicating it.

    Using replace function instead of adding in extra column.

    Thats fantastic. Thanks.


  • Moderators, Politics Moderators Posts: 41,209 Mod ✭✭✭✭Seth Brundle


    Be aware that two customers with the same name (assuming they are not unique) can screw this up but given what you have there isn't much you can do about it!


  • Advertisement
Advertisement