简体   繁体   English

在SQL Server中返回复杂数据类型

[英]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: 在我们的客户端中,我们使用c#检索数据,这是接口:

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. 那将是结果集的第一行,以及DepartmentID与上一行不同的任何行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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