基于变量结果集

时间:2013-11-24 20:41:15

标签: sql

我有三张桌子:

Main是具有唯一ID的小部件列表 Main_Properties是Main表中的外键,以及每个小部件的许多可能的Properties 属性是可能属性的表。它们包含以下数据:

Main
id name
1  Widget1

Main_Properties:
id prop  name
1  1     Colour
1  2     Metal


Properties:
prop prop_id text
1    1       Red
1    2       Green
1    3       Blue
1    4       Yellow
1    5       Black
1    6       White
2    1       Gold
2    2       Silver
2    3       Bronze
2    4       Aluminum
2    5       Copper
2    6       Metal

如果客户购买4个Widget1,那么他们应该只选择红色,绿色,蓝色或黄色。如果他们购买6,那么他们将获得相同的加上黑色或白色。无论购买数量多少,都应该选择金,银,铜,铝,铜或金属。

我有两个问题:

是否有更好的方法来构建表格 在sql中是否有一种方法可以限制颜色的选择而不是金属饰面的选择?

1 个答案:

答案 0 :(得分:0)

我要在Main_Properties中添加一列。

Main_Properties:
id prop  name    OfferAllChoices
1  1     Colour  0
1  2     Metal   1

然后我在StoredProc中使用两个参数。

DECLARE
    @id  INT,
    @qty INT

SELECT
    @id  = 1,
    @qty = 4

SELECT a.name, b.[prop], b.[prop_id], b.[text]
FROM   [Properties] b
JOIN   [Main_Properties] a ON a.prop = b.prop
WHERE 
    a.id = @id AND
    b.prop_id <= CASE a.offer WHEN 1 THEN 99999 ELSE @qty END