我想将列添加到表中。如果我的脚本的那部分执行,我也想在表中添加一些值。我该怎么办?
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
答案 0 :(得分: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;