Sql脚本使用一个表中的列并填充另一个表

时间:2013-10-10 22:29:40

标签: sql sql-server sql-server-2008 tsql sql-server-2008-r2

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

产品

ProductId Name 

评分

LevelId Cost ProductId

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

我现在需要一个脚本来获取所有产品ID并填充Rate表,以便我的结束输出如下所示:

LevelId Cost 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 个答案:

答案 0 :(得分:2)

查看CTEs (Common Table Expressions)

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可以使用算法创建虚拟数据表,因此无需手动创建充满可预测数据的表。使用六个UNION ALL的查询并不是那么糟糕,但数百或数千或数百万?如果您有超过100次递归且不超过32767次,则需要添加OPTION (MAXRECURSION n),其中n是您需要的循环数,或者如果您有超过32767次循环,则需要需要添加OPTION (MAXRECURSION 0)并警惕无限循环。

答案 1 :(得分: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的组合。

答案 2 :(得分: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

答案 3 :(得分: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