简体   繁体   中英

Return Complex data types in SQL server

I have two tables as below: One is department, the other is employee. Every department have several employees. Here is table definition:

Create table [dbo].[Department]
(
    ID int not null,
    Name varchar(100) not null,
    revenue int not null
)

Create table [dbo].[Employee]
(
    ID int not null,
    DepartmentID int not null,--This is foreign key to Department
    Name varchar(100) not null,
    Level int not null
)

Now, I want to query all the department with employee if department revenue is more than a value. So the result will contain a department list. For every department, it should also contain employee list.

In our client, we use c# to retrieve the data, here is the interface:

public List<Department> GetHighRevenueDepartmentWithEmployee(int revenueBar)
{
    throw new NotImplementedException();
}

My question here is: is it possible to get the compound result in one query/stored procedure. It is OK use one stored procedure to query multiple times, but the whole data must be return back to client in one time.(This is performance reason) How can we achieve this? I know we can define table values type here, but I cannot define a table value type which contain another table value as column inside.

Typically, you'd just return a result set with all of the columns from both tables:

SELECT
  d.ID as DepartmentID,d.Name as DepartmentName,d.Revenue,
  e.ID as EmployeeID,e.Name as EmployeeName,e.Level
FROM
   Department d
      inner join
   Employee e
      on d.ID = e.DepartmentID
WHERE
   d.revenue > @value
ORDER BY
   d.ID

Now, the data returned for the department will be repeated multiple times - once for every employee. But that's fine. Just use the first row for each new department and ignore it in the remaining rows. That would be for the first row of the result set, and for any row where the DepartmentID is different from the previous row.

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