0

我有一个 SQL Azure 表,其中包含组件和部件的信息。我需要编写一个存储过程来返回给定组件的正确部件列表。但是,由于某些行需要“覆盖”这一事实而变得复杂。

我的桌子看起来像:

ComponentID | Position | PartID | Area    | City   |
------------+----------+--------+---------+--------+
3           | 1        | F      | Europe  | None   |
3           | 1        | G      | England | None   |
3           | 1        | S      | England | London |
3           | 2        | H      | Europe  | None   |
3           | 2        | I      | England | None   |
3           | 3        | Q      | Europe  | None   |

这里的“覆盖”是,如果您更具体地了解某个位置,则应检索位置 X 中您能找到的最具体部分的详细信息。即基本版本可能可用,但其他版本可能优先。然后我需要忽略除了最具体的版本之外的所有内容。

我写的存储过程不工作。sproc 应该接受一个组件ID、一个区域和一个城市,并按照它们的位置顺序返回适当的组件。因此,以下示例应该成立:

Input: 3, Europe, None:

1 F
2 H
3 Q

Input: 3, England, None:

1 G
2 I
3 Q

Input: 3, England, London: 

1 S
2 I
3 Q

我手头没有失败的存储过程代码,但可以在几个小时内附上它......

4

1 回答 1

2

为了能够重用结果,我将创建一个函数而不是存储过程。如果你真的想要一个 SP,你可以使用我在下面创建的函数中的查询。

SQL小提琴

架构设置

create table tbl (
ComponentID int, Position int, PartID char(1), Area sysname   , City sysname );
insert into tbl select
3           , 1        , 'F'      , 'Europe'  , 'None'   union all select
3           , 1        , 'G'      , 'England' , 'None'   union all select
3           , 1        , 'S'      , 'England' , 'London' union all select
3           , 2        , 'H'      , 'Europe'  , 'None'   union all select
3           , 2        , 'I'      , 'England' , 'None'   union all select
3           , 3        , 'Q'      , 'Europe'  , 'None';

create function dbo.getComponents(
  @ComponentID int,
  @Area sysname,
  @City sysname)
returns table as return
with ranked as (
  select Position, PartID, rownum = row_number() over
    (partition by Position order by
     case when @Area=Area and @City=City then 1
          when @Area=Area then 2
          else 3 end)
    from tbl
)
select Position, PartID
from ranked
where rownum=1
GO

查询 1

select * from dbo.getComponents(3, 'Europe', 'None') order by PartID

结果

| POSITION | PARTID |
---------------------
|        1 |      F |
|        2 |      H |
|        3 |      Q |

查询 2

select * from dbo.getComponents(3, 'England', 'None') order by PartID

结果

| POSITION | PARTID |
---------------------
|        1 |      G |
|        2 |      I |
|        3 |      Q |

查询 3

select * from dbo.getComponents(3, 'England', 'London') order by PartID

结果

| POSITION | PARTID |
---------------------
|        2 |      I |
|        3 |      Q |
|        1 |      S |
于 2013-05-03T12:10:53.670 回答