Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to Set a variable inside a Function with Select SQL

I need to make a function that returns a table from employees where they work under a specific employee.

I tried to write the following but I’m getting error:

An INSERT statement cannot contain a SELECT statement that assigns values to a variable.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

CREATE FUNCTION GetSubTree (@SupervisorID int)
RETURNS @Result TABLE(
    Id  INT     PRIMARY KEY NOT NULL,
    HIERARCHY   HIERARCHYID    NOT NULL ,
    FirstName   NVARCHAR(50)    NOT NULL,
    LastName   NVARCHAR(50)    NOT NULL,
    NationalCode    bigint    NOT NULL,
    EmployeeRole    NVARCHAR(3) NOT NULL
)
AS
BEGIN
    DECLARE @hi HIERARCHYID;
    DECLARE @hiT TABLE(
        HI HIERARCHYID
    )
    INSERT into @hiT
    SELECT Top 1 @hi= HIERARCHY
    FROM dbo.Company as C1
    WHERE C1.Id = @SupervisorID;
    INSERT INTO @Result
    SELECT * 
    FROM   dbo.Company as C
    WHERE   C.HIERARCHY.IsDescendantOf(@hi) = 1 AND C.Id != @SupervisorId;
    RETURN;
End;

Any help is appreciated

>Solution :

Split the commands

CREATE FUNCTION GetSubTree (@SupervisorID int)
RETURNS @Result TABLE(
    Id  INT     PRIMARY KEY NOT NULL,
    HIERARCHY   HIERARCHYID    NOT NULL ,
    FirstName   NVARCHAR(50)    NOT NULL,
    LastName   NVARCHAR(50)    NOT NULL,
    NationalCode    bigint    NOT NULL,
    EmployeeRole    NVARCHAR(3) NOT NULL
)
AS
BEGIN
    DECLARE @hi HIERARCHYID;
    DECLARE @hiT TABLE(
        HI HIERARCHYID
    )

    SELECT Top 1 @hi= HIERARCHY
    FROM dbo.Company as C1
    WHERE C1.Id = @SupervisorID;

    INSERT into @hiT
    VALUES
    (@hi)
    
    INSERT INTO @Result
    SELECT * 
    FROM   dbo.Company as C
    WHERE   C.HIERARCHY.IsDescendantOf(@hi) = 1 AND C.Id != @SupervisorId;
    RETURN;

End;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading