将行插入表中,其中值不在列中

时间:2011-11-19 17:32:39

标签: sql sql-server tsql

我有一个包含三列的表:DayKeyValue。如果Key列中没有值,我希望能够插入它:

DAY | KEY | VALUE
------------------
Mon   Run   50    
Mon   Bike  20
Tues  Run   25
Tues  Bike  60
Wed   Run   20
Wed   Swim  5

我希望能够从列中识别缺少“Bike”值的行并插入它。所以会有一个额外的行

Wed Bike 20

我应该如何实现这一目标?

1 个答案:

答案 0 :(得分:1)

你可以试试这个吗?这是硬编码的方法:

INSERT INTO <yourtable> (day, key, value)
SELECT DISTINCT t1.day AS day, 'Bike' as key, 20 as value
FROM
    <yourtable> AS t1
    LEFT OUTER JOIN 
    (SELECT day, key FROM <yourtable> WHERE key='Bike') AS t2
    ON t1.day = t2.day
WHERE t2.key IS NULL;

或者,如果可以,请使用存储过程(这将允许您选择活动和值:

CREATE PROCEDURE dbo.InsertActivityWhereMissing 
      @activity VARCHAR(50)
    , @activityValue INT
AS
BEGIN
    INSERT INTO <yourtable> (day, key, value)
    SELECT t1.day AS day, @activity as key, @activityValue as value
    FROM
        (SELECT day FROM <yourtable> GROUP BY day) AS t1
        LEFT OUTER JOIN 
        (SELECT day, key FROM <yourtable> WHERE key = @activity) AS t2
        ON t1.day = t2.day
    WHERE t2.key IS NULL;
END

这样,您就可以针对任何特定"activity"执行相同的操作(我只是这样命名,但我指的是RunBike,{{ 1}}或其他任何东西)