简体   繁体   中英

Handling foreign keys in T-SQL select stored procedure?

I'm writing stored procedures to get data based on a given id and that's all well and good, but some of the columns are foreign keys and what I need are their values. How do I do all of this within a stored procedure?

For reference, I will be using ASP.NET (haven't learned it yet) to call these stored procedures and update the website.

For instance, in the AdventureWorks database:

CREATE PROCEDURE spLoadProduct
AS
BEGIN
    SET NOCOUNT ON;

    SELECT 
        [ProductID], [Name],
        [ProductCategoryID], [ProductModelID]
    FROM 
        [SalesLT].[Product]
END

Screenshot of current SP result

What I want is for the last two columns to return the actual category and model names, not the foreign keys. Is the standard practice to do it all in one stored procedure as I am trying to do?

Maybe I am misinterpreting your question, but you can include joins in stored procedures.

Example if you have where afkey links out to table 2

Table_1:                      Table_2:
id  name   afkey              akey otherinfo
1   fred   1                   1     info
2   jon    2                   2     other
3   abbie  3                   3     more info

If you want to display the otherinfo column instead of the afkey foreign key

You could have:

create PROCEDURE spLoad
AS
    BEGIN
        SET NOCOUNT ON;
        SELECT NAME, OTHERINFO
        FROM TABLE_1
        INNER JOIN TABLE_2 
        ON TABLE_1.afkey = TABLE_2.akey
    END

You can use INNER JOIN to join the parent table to the child tables. In this case, the child tables are ProductCategory, and ProductModel.

CREATE PROCEDURE spLoadProduct 
AS
BEGIN

    SELECT
        p.ProductID
        , p.Name
        , p.ProductCategoryID
        , p.ProductModelID
        , ProductCategoryName = pc.Name
        , ProductModelName = pm.Name
    FROM 
        SalesLT.Product p
        INNER JOIN SalesLT.ProductCategory pc ON p.ProductCategoryID = pc.ProductCategoryID
        INNER JOIN SalesLT.ProductModel pm ON p.ProductModelID = pm.ProductModelID;

END

Inner join tutorial: http://www.w3schools.com/sql/sql_join_inner.asp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM