我要在查询分析器里面执行,请问下面如何写:IF 表1中没有字段A THEN
BEGIN
  --添加字段A
  ALTER TABLE 表1 ADD A int
  GO
END;
ELSE
BEGIN
  ALTER TABLE 表1 drop column A --先删除字段A;
  GO
  --再添加字段A
  ALTER TABLE 表1 ADD A int
  GO
END;

解决方案 »

  1.   

    判断media表中是否有res字段并创建
    use master
    go
    if not exists(select * from dbo.syscolumns where id in (select id from dbo.sysobjects where name='media' and type='U') and name ='rese')
    begin
    ALTER TABLE [dbo].[media]  ADD res int NULL 
    end
    else
             ALTER TABLE [dbo].[media]  DROP COLUMN  res 
             ALTER TABLE [dbo].[media]  ADD res int NULL 
    beginend
    GO
      

  2.   

    上面的写错了一个地方判断media表中是否有res字段并创建
    use master
    go
    if not exists(select * from dbo.syscolumns where id in (select id from dbo.sysobjects where name='media' and type='U') and name ='res')
    begin
    ALTER TABLE [dbo].[media]  ADD res int NULL 
    end
    else
             ALTER TABLE [dbo].[media]  DROP COLUMN  res 
             ALTER TABLE [dbo].[media]  ADD res int NULL 
    beginend
    GO
      

  3.   

    IF EXISTS(SELECT 1 FROM SYSCOLUMNS WHERE ID=OBJECT_ID('TABLE1') AND NAME='A') 
    ALTER TABLE 表1 ADD A int 
    ELSE
    BEGIN
      ALTER TABLE 表1 drop column A --先删除字段A;
      GO
      --再添加字段A
      ALTER TABLE 表1 ADD A int
    END;
      

  4.   

    IF EXISTS(SELECT 1 FROM SYSCOLUMNS WHERE ID=OBJECT_ID('TABLE1') AND NAME='A') 
    BEGIN
      ALTER TABLE 表1 drop column A
    END
    ALTER TABLE 表1 ADD A int