在SQL Server

时间:2016-05-02 05:37:37

标签: sql sql-server tsql stored-procedures

我的问题是:如何从table1插入到table2?

表1是:

Number Category Value
10        1      1000
10        2      5000
12        3      4000

表2是:

number  Category1 Category2 Category3
 10        1000      5000      NULL
 12         NULL      NULL      4000

我需要这样做(我的类别是限制的。)

我的解决方案:我创建了一个存储过程,它获取一个参数并插入到table2中,如下所示:

CREATE proc [dbo].[UpdateMemberActivityCategory]
    (@Number nchar(11),
     @Value int,
     @Type int)
AS
BEGIN
    IF (NOT EXISTS(SELECT * FROM MemberActivityCategory WHERE (Number=@Number))) 
    BEGIN 
        INSERT INTO MemberActivityCategory(Number) 
        VALUES(@Number);

        IF(@Type = 2)
        BEGIN
            UPDATE MemberActivityCategory  
            SET ArtAndCulture = @Value 
            WHERE (Number = @Number)    
        END

        IF(@Type = 3)
        BEGIN
            UPDATE MemberActivityCategory  
            SET Learn = @Value 
            WHERE (Number = @Number)        
        END

        IF(@Type = 4)
        BEGIN
            UPDATE MemberActivityCategory  
            SET Business = @Value 
            WHERE (Number = @Number)        
        END
END

我将这个程序称为:

select *, myProc(t.Number,1,t.category)
from myTable t

我的解决方案不正确吗?什么是最好的方法呢?

2 个答案:

答案 0 :(得分:0)

您无法在选择查询中执行存储过程。请尝试以下查询,将table1的数据插入table2

INSERT INTO table2(number,  Category1, Category2, Category3)
SELECT  DISTINCT Number 
        ,(SELECT TOP 1 t1.Value FROM table1 t1 
            WHERE t1.Number = t.Number and t1.Category = 1 )
        ,(SELECT TOP 1 t1.Value FROM table1 t1 
            WHERE t1.Number = t.Number and t1.Category = 2 )
        ,(SELECT TOP 1 t1.Value FROM table1 t1 
            WHERE t1.Number = t.Number and t1.Category = 3 )
FROM    table1 t

答案 1 :(得分:0)

您可以使用a pivot table

WITH cte AS (
    SELECT * FROM (
        VALUES
            (10, 1, 1000),
            (10, 2, 5000),
            (12, 3, 4000)
        ) AS a (Number, Category, Value)
)

SELECT Number AS Number, [1], [2], [3]
FROM cte
PIVOT
(
   SUM(Value)
   FOR Category IN ([1], [2], [3])
) AS PivotTable;

结果:

10  1000    5000    NULL
12  NULL    NULL    4000