1

我有两张表产品表和费率表。

产品

ProductId Name 

速度

LevelId Cost ProductId

每个产品有 7 个级别,每个级别的成本为 100、200.... 700。

我现在需要一个脚本来获取所有产品 ID 并填充费率表,这样我的最终输出将如下所示:

速度

LevelId 成本 ProductId

1          100    1  
2          200    1  
3          300    1  
4          400    1  
5          500    1  
6          600    1  
7          700    1  
1          100    2  

等等

目前我手动插入前 7 行,然后为每个产品 ID 运行以下查询

INSERT INTO dbo.Rate (LevelID, Cost, ProductId)
    SELECT LevelID, Cost, ProductId FROM dbo.Rate WHERE ProductId = 1

你能指导我如何完全自动化我的工作吗?

4

4 回答 4

2

看看CTE(通用表表达式)

WITH CTE AS
(SELECT 1 as LevelID , 100 as Cost
 UNION ALL
 SELECT LevelID + 1 , Cost + 100 
 FROM CTE 
 WHERE LevelID < 7)
INSERT INTO Rate
SELECT CTE.LevelID, CTE.Cost, Product.ProductID
FROM CTE CROSS JOIN Product

CTE 可以使用算法创建虚拟数据表,因此无需手动创建充满可预测数据的表。使用 6 UNION ALLs 的查询还不错,但是数百或数千或数百万呢?如果您有超过 100 次递归且不超过 32767,则需要在OPTION (MAXRECURSION n)wheren中添加您需要的循环数,或者如果您有超过 32767 个循环,则需要添加OPTION (MAXRECURSION 0)并警惕无限循环.

于 2013-10-10T22:53:11.590 回答
1
CREATE TABLE #temp (levelid INT)

INSERT INTO #temp (levelid) 
SELECT 1
UNION ALL
SELECT 2
UNION ALL 
SELECT 3
UNION ALL 
SELECT 4 
UNION ALL 
SELECT 5
UNION ALL  
SELECT 6
UNION ALL 
SELECT 7

insert into dbo.rate
SELECT levelid, (levelid * 100) AS cost, productid
FROM dbo.Product 
CROSS JOIN #temp

DROP TABLE #temp

我创建了一个具有 7 个级别的临时表,然后使用它。交叉连接创建了每个级别和每个产品 ID 的组合。

于 2013-10-10T22:45:16.037 回答
1
 INSERT INTO Rate
 SELECT   bs.level, bs.costs, P.productid
 FROM
     (SELECT 1 as level, 100 as cost
      UNION ALL
      SELECT 2 as level, 200 as cost
      UNION ALL
      SELECT 3 as level, 300 as cost
      UNION ALL
      SELECT 4 as level, 400 as costs
      UNION ALL
      SELECT 5 as level, 500 as costs
      UNION ALL
      SELECT 6 as level, 600 as costs
      UNION ALL
      SELECT 7 as level, 600 as costs) bs,
   Product P
于 2013-10-10T22:46:27.243 回答
1

只是把它扔在那里,假设你可以访问master..spt_values桌子,你可以做这个小技巧:

insert into rate
select distinct s.number, s.number * 100, p.productid
from product p 
  join master..spt_values s
     on s.number > 0 and s.number < 8
于 2013-10-10T23:03:34.263 回答