我想插入尚未插入的记录

时间:2016-01-08 10:34:19

标签: c# sql sql-server

INSERT INTO Timetable values ('E-465458',1,1,8,10,11) 
SELECT StaffID, ClassTimingId,WeekDayId,DepartmentId,ClassID,SectionID
FROM TimeTable
WHERE  EXISTS (SELECT *
          FROM Timetable
          WHERE WeekDayId = 1 AND DepartmentId = 8  and ClassTiminng = 1  ) ;

如果WeekdayID是alredy 1而DepartmentId=8ClassTiming=1,那么我的表名为时间表,然后不要插入记录它搜索表格中的所有行

3 个答案:

答案 0 :(得分:3)

试试这个:

IF NOT EXISTS (
        SELECT *
        FROM Timetable
        WHERE WeekDayId = 1
            AND DepartmentId = 8
            AND ClassTiming = 1
    )
BEGIN
    INSERT INTO Timetable (StaffID, ClassTimingId, WeekDayId, DepartmentId, ClassID, SectionID)
    VALUES ('E-465458', 1, 1, 8, 10, 11)
END

答案 1 :(得分:0)

同意irshad,您可以尝试这样来优化查询:

- (instancetype) init
{
    if (self = [super init]){
        // REGISTER for KVO
        [self addObserver:self 
               forKeyPath:@"parent" 
                  options:NSKeyValueObservingOptionNew
                  context:NULL];
    }

    return self;
}

- (void) dealloc 
{
    // UNREGISTER from KVO
    [self removeObserver:self forKeyPath:@"parent" context:NULL];
}

// Method that is called when any keyPath you subscribed to is modified
- (void)observeValueForKeyPath:(NSString *)keyPath
                  ofObject:(id)object
                    change:(NSDictionary *)change
                   context:(void *)context
{
    // (Check keypath in case you are observing several different
    //  properties. Otherwise, remove if statement:)

    if ([keyPath isEqualToString:@"parent"]) {

        // parent node changed; do something
    }
}

答案 2 :(得分:0)

您无法同时执行VALUESSELECT

INSERT INTO Timetable  
SELECT 'E-465458',1,1,8,10,11
WHERE NOT EXISTS (SELECT *
          FROM Timetable
          WHERE WeekDayId = 1 AND DepartmentId = 8  and ClassTiminng = 1  ) ;

或者更好地切换到MERGE:

MERGE INTO Timetable AS tgt 
USING VALUES ('E-465458',1,1,8,10,11) AS src (StaffID, ClassTimingId,WeekDayId,DepartmentId,ClassID,SectionID)
  ON tgt.WeekDayId     = src.WeekDayId
 AND tgt.DepartmentId  = src.DepartmentId
 AND tgt.ClassTimingId = src.ClassTimingId
WHEN NOT MATCHED
THEN INSERT (src.StaffID, src.ClassTimingId,src.WeekDayId,src.DepartmentId,src.ClassID,src.SectionID)