Add a new table column to specific ordinal position in Microsoft SQL Server

后端 未结 9 935
北海茫月
北海茫月 2020-11-27 20:16

Is it possible to add a column to a table at a specific ordinal position in Microsoft SQL Server?

For instance, our tables always have CreatedOn, CreatedBy, LastModi

相关标签:
9条回答
  • 2020-11-27 20:45

    go into SQL Server management Studio, and "design" an existing table. Insert a column in the middle, right click in an empty area and select Generate Change Script...

    Now look at the script it creates. it will basically create a temp table with the proper column order, insert the data from the original table, drop the original table, and rename the temp table. This is probably what you'll need to do.

    You may also need to uncheck this option to allow creation of change scripts

    0 讨论(0)
  • 2020-11-27 20:47

    TFS 2013 will do this for you automatically.

    Add the new column(s) to your table anyway you like, and then commit your changes to TFS. From there you can open the table's sql file in Visual Studio and manually move the order of the columns in the T-SQL CREATE script. Then you can update your target database by using VS's schema compare tool found under Tools > SQL Server > New Schema Comparison. Choose your Database project with your change as the source, and the database you want to update as the target. Compare, select the table's script, and Update. VS will drop and add automatically. All your data will be safe, and indexes too.

    0 讨论(0)
  • 2020-11-27 20:47

    Select all the columns into a temp table, and create a new table with the new column you want. Then drop the old table, select all the columns from the temp table, and insert them into the new table with the reordered column. No data is lost.

    SELECT * FROM TEMP
    SELECT * FROM originaltbl
    SELECT * FROM #Stagintbl
    
    DECLARE @ColumnName nvarchar(max);
    SET @ColumnName=(SELECT
        DISTINCT STUFF((
            SELECT ',' + a.COLUMN_NAME
            FROM (
                SELECT Column_name 
                FROM INFORMATION_SCHEMA.COLUMNS 
                WHERE TABLE_NAME='originaltbl') a
            for xml path('')
        ),1,1,'') AS ColumnName)
    
    DECLARE @Sqlquery nvarchar(max)
    SET @Sqlquery = 'SELECT ' + @ColumnName + ' FROM #Stagintbl' + '';
    INSERT INTO originaltbl
    EXECUTE(@Sqlquery)
    
    0 讨论(0)
提交回复
热议问题