[英]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. 我正在编写存储过程以根据给定的ID获取数据,这很好,但是有些列是外键,我需要的是它们的值。 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. 作为参考,我将使用ASP.NET(尚未了解)来调用这些存储过程并更新网站。
For instance, in the AdventureWorks database: 例如,在AdventureWorks数据库中:
CREATE PROCEDURE spLoadProduct
AS
BEGIN
SET NOCOUNT ON;
SELECT
[ProductID], [Name],
[ProductCategoryID], [ProductModelID]
FROM
[SalesLT].[Product]
END
Screenshot of current SP result 当前SP结果的屏幕截图
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 如果您有afkey链接到表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 如果要显示otherinfo列而不是afkey外键
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. 您可以使用INNER JOIN将父表联接到子表。 In this case, the child tables are ProductCategory, and ProductModel. 在这种情况下,子表是ProductCategory和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 内部加入教程: http : //www.w3schools.com/sql/sql_join_inner.asp
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.