C# SQL create table IF it doesn't already exist

This question already has an answer here:

  • Check if table exists in SQL Server 21 answers

  • The syntax of that under SQL Server 2005 is

    IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[tablename]') AND type in (N'U'))
    BEGIN
      -- create
    END
    

    In your code, where is the = FALSE or NOT keyword?


    Your SQL is creating the table if it does exist and not if it doesn't.

    Change the SQL to read IF NOT EXISTS .


    You can also look into using Microsoft SMO objects. I prefer to work SMO objects and let them do the work for me if possible instead of executing SQL text through code.

    Using the SMO Database object you can do the following.

    Database db = myServer.Databases["MyDB"];
    
    if (! db.Tables.Contains("NewTable"))
    {
    
        Table tbl = new Table(db, "NewTable");
    
        Column col1 = new Column(tbl, "Column1", DataType.Varchar(10));
        col1.Nullable = true;
        tbl.Columns.Add(col1);
    
        tbl.Create();
    
    }
    

    http://www.mssqltips.com/tip.asp?tip=1826

    链接地址: http://www.djcxy.com/p/94438.html

    上一篇: 你如何使用SQL来查看表是否存在?

    下一篇: 如果它不存在,C#SQL创建表