需求是这样的,我需要扩展表,增加一列point,增加前我需要先判断是否存在该列,若不存在则添加列,反之则不做任何操作
我的sql语句总是报错,而括号中的语句是可以执行的
IF exists(select  column_name from information_schema.columns where table_schema='test' and table_name='t_user' and column_name='point' ) 
select 'tt';求教正确写法

解决方案 »

  1.   

    MYSQL中不支持这种语法。  如果是在存储过程中,你可以先返回 select count(*) into x, 然后 IF x>0 再决定是否执行括号中的语句。如果在非存储过程中,则没有办法,只能在自己的程序中判断。
      

  2.   

    只能在SP中使用
    DELIMITER $$
    CREATE PROCEDURE gg()
    BEGIN
    IF EXISTS(SELECT  column_name FROM information_schema.columns WHERE table_schema='test' AND table_name='t_user' AND column_name='point' ) THEN 
    SELECT 'tt';
    END IF;
    END$$
    DELIMITER ;
      

  3.   

    delimiter$$
    create procedure gg()
    begin
    if exists(select column_name from information_schema.columns where 
    table_schema='test' and table_name='t_user' andn column_name='point')
    then
    select 'tt';
    end if;
    end$$
    delimiter$$;
      

  4.   

    delimiter$$
    create procedure gg()
    begin
    if exists(select column_name from information_schema.columns where  
    table_schema='test' and table_name='t_user' andn column_name='point')
    then
    select 'tt';
    end if;
    end$$
    delimiter;
      

  5.   

    楼上做法是否行得通没在mysql中验证过,但我不想这样用,也不推荐这样的做法,若语句报错,是否会对后面的产生操作产生影响呢
      

  6.   

    select  @testresult:=count(*) from information_schema.columns where   
    table_schema='test' and table_name='t_user' andn column_name='point' ;
    select @testresult
    if (@testresult='1') then
    select 'yes';
    end if
    到select @testresult 这没问题,但是if语句怎么又报脚本错误呢?? mysql与Sql Server差别很大啊
      

  7.   

    MYSQL中不支持匿名块,也就是说这类过程性语句IF,THEN必须放在存储过程中执行。