从存储过程获取表外键

时间:2016-10-17 18:55:00

标签: sql stored-procedures

我有Employee表,我有BranchOfficeId foreignKey。如何修改存储过程以获取Employee Table的所有BranchOfficeId?。

存储过程:

USE [AM_DB]
GO
/****** Object:  StoredProcedure [dbo].[GetEmployeeTraining]    Script Date: 17/10/2016 10:47:34 a. m. ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[GetEmployeeTraining]
    -- Add the parameters for the stored procedure here
     @IdTraining INT = null
    ,@IdArea int = null
    ,@IdDepartment int = null
    ,@Type VARCHAR(15) 
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    DECLARE @query varchar(100)

    Create Table #Type(
    value int
    )

    SET @query = 'INSERT INTO #Type(value) VALUES ' + @Type
    EXEC (@query)

    -- Insert statements for procedure here
    SELECT 
          0 AS Id
         ,0 AS IdTraining
         ,e.ID AS IdEmployee
         ,e.Code AS Code
         ,e.Name +' ' +e.LastName + ' '+ e.SurName AS Name
         ,e.CURP
         ,e.RFC 
         ,e.AdmissionDate
         ,a.Description AS Area
         ,d.Description AS Department
         ,0.0 AS Hours
         ,0.0 AS Score
         ,e.Empresa
        FROM [dbo].[Employee] e (NOLOCK)
        LEFT JOIN [dbo].[Area] a (NOLOCK)
            ON e.Area = a.Id
        LEFT JOIN [dbo].[Department] d (NOLOCK)
            ON d.Id = e.Department
        WHERE 
            ((e.Id NOT IN (SELECT IdEmployee FROM [dbo].[TrainingEmployee] (NOLOCK) WHERE IdTraining = @IdTraining)) OR @IdTraining IS NULL)
            AND 
            ((e.Area = @IdArea) OR @IdArea IS NULL)
            AND
            ((e.Department = @IdDepartment) OR @IdDepartment IS NULL)
            AND
            (e.Type IN (SELECT value FROM #Type))


DROP TABLE #Type;
END
我支持。如果有人能解释我存储过程如何工作以及我需要做些什么来添加这些字段。我真的很感激

1 个答案:

答案 0 :(得分:0)

如果BranchOfficeId位于Employee表中,您唯一需要做的就是将其添加到列列表中(如下所示)。以下是有关存储过程的问题的答案... What is a stored procedure?

SELECT 0 AS Id ,0 AS IdTraining ,e.BrachOfficeId --Add this line ,e.ID AS IdEmployee ,e.Code AS Code ,e.Name +' ' +e.LastName + ' '+ e.SurName AS Name ,e.CURP ,e.RFC ,e.AdmissionDate ,a.Description AS Area ,d.Description AS Department ,0.0 AS Hours ,0.0 AS Score ,e.Empresa FROM [dbo].[Employee] e (NOLOCK) LEFT JOIN [dbo].[Area] a (NOLOCK) ON e.Area = a.Id LEFT JOIN [dbo].[Department] d (NOLOCK) ON d.Id = e.Department WHERE ((e.Id NOT IN (SELECT IdEmployee FROM [dbo].[TrainingEmployee] (NOLOCK) WHERE IdTraining = @IdTraining)) OR @IdTraining IS NULL) AND ((e.Area = @IdArea) OR @IdArea IS NULL) AND ((e.Department = @IdDepartment) OR @IdDepartment IS NULL) AND (e.Type IN (SELECT value FROM #Type))