我现在需要执行一条 创建表的 SQL 语句 CREATE Table
 SqlCommand 中用什么方法执行。可以得到 是否创建成功的信息。
 
 我只找到了 返回结果为  放回影响行数、放回结果集、放回结果集中第一行第一列
这几个执行语句的方法。用这些方法执行添加表的语句 都会出现异常。
但实际 表是创建成功了!请各位大大指点一下!

解决方案 »

  1.   

         额。。 sqlcommand好像不可以执行这个吧
      

  2.   

    ExecuteNonQuery
    来执行你的语句
      

  3.   


    cmd.ExecuteNonQuery() 方法的返回值 是影响行数啊!还是只会报异常。
    还是我的使用方法不对?
      

  4.   


    不会啊! 表是床架成功了!只是返回的是异常。
    sqlcommand
    要是不能执行这些东西的话! 我们不就不能创建表了吗!
      

  5.   


    这个还真没用过!
    试着用一下!
    sqlcommand 就真的的不到 正确的返回值吗?
      

  6.   

    可以用组合的sql过程结合SqlCommand的ExecuteScalar方法实现
    以下分开来写(为看起来方便):if not exists (select 1 from dbo.sysobjects where id = object_id(N'[new_table]') 
    and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    begin
    create table new_table(
    name varchar(50)
    )
    end
    goif exists (select 1 from dbo.sysobjects where id = object_id(N'[new_table]') 
    and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    select 'true'
    else
    select 'false'
    go
        /// <summary>
        /// 创建表结构(示例代码)
        /// </summary>
        /// <param name="sql">这里即为上面的sql段 一定要注意空格且分段清晰 保证语法无误</param>
        /// <returns></returns>
        public bool CreateTable(string sql)
        {
            bool isCreate=false;
            SqlCommand cmd = new SqlCommand(sql, new SqlConnection("connectionString"));
            cmd.Connection.Open();
            try
            {
                object ret = cmd.ExecuteScalar();
                cmd.Connection.Close();                
                if (ret != null)
                {
                    Boolean.TryParse(ret.ToString(), out isCreate);
                }
            }
            catch (System.Exception e)
            {
             //异常处理
            }
            finally
            {
                if (cmd.Connection!=null&&cmd.Connection.State==ConnectionState.Open)
                {
                    cmd.Connection.Close();
                }
            }
            return isCreate;
        }当然 如果每次都要创建新表 sql可改为:
    if exists (select 1 from dbo.sysobjects where id = object_id(N'[new_table]') 
    and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table new_table
    go
    create table new_table(
    name varchar(50)
    )
    goif exists (select 1 from dbo.sysobjects where id = object_id(N'[new_table]') 
    and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    select 'true'
    else
    select 'false'
    go