-1

我想在表格中添加列。如果我的脚本的那部分执行,我还想向表中添加一些值。我该怎么做 ?

  if not exists (select 1 from sys.columns 
                 where object_id = object_id('CAT_MASSUPDATETASKPARAM') 
                 and name = 'ValueBoolean' )
  begin
           alter table CAT_MASSUPDATETASKPARAM add ValueBoolean bit NULL 
  end
  go

  IF (the first script was running do this script )
       INSERT INTO CAT_MASSUPDATETASKPARAM ( ParentTaskIK,    
              ParamType,ParamName,ValueInt,ValueStr,ValueBoolean)
       SELECT ParentTaskIK, 'Boolean','SHOW_CURRENT',NULL,NULL,1
       FROM   CAT_MASSUPDATETASKPARAM ,CAT_MASSUPDATETASK
       WHERE  CAT_MASSUPDATETASKPARAM.ParentTaskIK = CAT_MASSUPDATETASK.Id
       AND    CAT_MASSUPDATETASK.MassUpdateType in ('somthing','somthing1')
       GROUP BY ParentTaskIK  
 go
4

1 回答 1

4

只有在第一个添加列时,您才希望第二部分运行......将它放在同一个开始-结束块中。但是您需要动态 SQL,因为在编译时会检查列是否存在。

if not exists (select 1 from sys.columns where object_id =     object_id('CAT_MASSUPDATETASKPARAM') and name = 'ValueBoolean')
begin
    alter table CAT_MASSUPDATETASKPARAM  add ValueBoolean bit NULL;
    EXEC ('
    INSERT INTO CAT_MASSUPDATETASKPARAM ( ParentTaskIK,    ParamType,ParamName,ValueInt,ValueStr,ValueBoolean)
        select ParentTaskIK, ''Boolean'',''SHOW_CURRENT'',NULL,NULL,1
        from CAT_MASSUPDATETASKPARAM ,CAT_MASSUPDATETASK
        where CAT_MASSUPDATETASKPARAM.ParentTaskIK = CAT_MASSUPDATETASK.Id
        and CAT_MASSUPDATETASK.MassUpdateType in (''somthing'',''somthing1'')
        group by ParentTaskIK     ');
end
go

否则,在同一会话中,您可以使用临时表或一些此类标记:

if not exists (select 1 from sys.columns where object_id =     object_id('CAT_MASSUPDATETASKPARAM') and name = 'ValueBoolean')
begin
    alter table CAT_MASSUPDATETASKPARAM  add ValueBoolean bit NULL;
    create table #marker (id int);
end;
GO
if object_id('tempdb..#marker') is not null
    INSERT INTO CAT_MASSUPDATETASKPARAM (
        ParentTaskIK,ParamType,ParamName,ValueInt,ValueStr,ValueBoolean)
    select ParentTaskIK, 'Boolean','SHOW_CURRENT',NULL,NULL,1
        from CAT_MASSUPDATETASKPARAM ,CAT_MASSUPDATETASK
        where CAT_MASSUPDATETASKPARAM.ParentTaskIK = CAT_MASSUPDATETASK.Id
        and CAT_MASSUPDATETASK.MassUpdateType in ('somthing','somthing1')
        group by ParentTaskIK;
于 2012-12-04T08:54:34.673 回答