Need steps for Alter the table - sql-server

Whenever I make changes to a table structure in SSMS, there is a alert raised:
saving the changes is not permitted.the changes u have been made to the following tables to be dropped and recreate..

Some changes cause a table to be dropped and recreated. One such example is adding a column to the middle of a table rather than to the end.
You can do one of two things:
Option 1
Use TSQL to make your changes and add the column to the end (or the equivalent non table-drop option for your specific edit)
Option 2
Alter the default behavior of SSMS (warning - this is a very dangerous thing in production environments)
Open SQL Server 2008 Management Studio (SSMS). In the menu, go to Tools / Options. In the Navigation pane, expan Designers, and select "Table and Database Designers".
Under Table options, uncheck “Prevent saving changes that require the table re-creation” option and click OK.

I've seen those kinds of messages most often come up when the changes you are making could potentially cause data to be truncated. So, if you were changing an nvarchar(20) to nvarchar(10), that would come up. It doesn't matter if the column only contains data that is 2 characters long, it only looks at the data type. There may be other reasons and other flavors of that message, but mostly they follow the same reasoning: If the change would cause the table to be more restricted in the data it could hold, it wants to do radical surgery.

Related

SQL Server: log modifications

I have a SQL Server and I need to log any changes made to a set of tables and their fields. Information needed is the user, the date time, the related table / field and the new value.
I saw the Change Data Capture (CDC) feature which seems perfect but it requires a non-standard version - and I have (and I may only have) the standard version.
The single solution I see is to use trigger, but it may cause performance troubles (it blocks the related table while the log is being inserted). Is there any other solution?
If you don't want triggers to do this, then define a stored procedure that will insert entries in log, after inserting the data into the table successfully.
it blocks the related table while the log is being inserted
Most probably you are using FOR INSERT for trigger, i think you should try AFTER INSERT

SQL Server table changes

So I've noticed over the past few weeks that changing tables in SQL Server is very difficult, such as specifying a new primary key column or changing a column definition (ie. changing it's datatype). Half of the time I have to drop the table and start over. Or even re-ordering columns in a table results in about a half hour of working (even though it doesn't really matter to the databse engine what order they are in, but I like to have things in logical order).
Are there any simpler ways to make changes to tables like this without having to go through headaches of dropping tables or recreating them. Most of the time I get an error saying that the table has to be dropped and recreated but apparently SQL server can't do this. I don't want to turn off the "Prevent table changes from requiring a table to be dropped" option because of the possiblye problems it can cause later.
Sometimes, for example, I can cheat and generate a CREATE TABLE script and then change the definition of a table in the script, drop the actual table, and create it again with the script ,but sometimes this doesn't work. And re-ordering columns is a pain and a problem, or even changing data types in a column that's already in the table, or setting a primary key, or changing a field from "NULL" to "NOT NULL" using the checkbox.
Any ideas on how to better manage the tables and make changes? It frustrates me that Microsoft did not follow the SQL standard on some of its ALTER TABLE commands, among other things. In MYSQL this would be a lot easier, but we are using SQL Server unfortunately.

Schema change table rebuild

I'm working on a script to keep table schemas synchronized.
Is there an exhaustive list of actions done to a table schema in MS SQL that requires the table to be dropped and recreated and the data to be reinserted?
You may be better off standardizing on the CREATE-COPY-DROP-RENAME (CCDR) strategy and only attempting an in-place alter in the few scenarios where your DDL will not require a rebuild rather than trying to compile the exhaustive list. This is the strategy described here: link.
AFAIK, you are only permitted to add columns to an existing table (without rebuilding) if the column is:
added to the end of the table AND
is nullable or has a default constraint
In all other cases, MSSQL will potentially fail if it does not know what to use as a value in the rows of the newly added column or data loss is a result (truncation for example). Even defaulted columns added in the middle will force a rebuild.
To further complicate things, in some cases the success of your deploy will depend on the type of data in the table, and not simply the schema involved. For example, altering a column length to a greater value (varchar(50) --> varchar(100)) will likely succeed; however, decreasing the length is only sometimes permitted. Migrating data type changes is another tricky mess.
In short, I would always rebuild and rarely alter in place.
--
To illustrate in-row data affecting outcome:
create table dbo.Yak(s varchar(100));
insert into dbo.Yak
values(replicate('a', 100));
go
-- attempt to alter datatype to 50 (FAIL: String or binary data would be truncated.)
alter table dbo.Yak
alter column s varchar(50);
go
-- shorten the data in row to avoid data loss
delete from dbo.Yak;
insert into dbo.Yak
values(replicate('a', 50));
go
-- again, attempt to alter datatype to 50 (SUCCESS)
alter table dbo.Yak
alter column s varchar(50);
go
select len(s),* from dbo.Yak;
go
--cleanup
drop table dbo.Yak;
go
In Management Studio, select the table you want to change and right-click Design. Change the datatype of a column in the table design window (tested with int to money).
Instead of saving, right-click in the window and select "Generate Change Script". Copy the SQL statements from the dialog.
*) In previous versions (SQL2000), any changes would recreate the whole table (as far as I remember). It seems that renaming and adding columns have been optimized to ALTER TABLE statements.
I've gotten pretty spoiled by using Visual Studio Database Projects to manage this sort of thing. Once my schema is imported into a project, I can make whatever change I want, and the VSDP will figure out whether the change can be done w/o dropping objects (with an ALTER, for example), or whether it needs to create a new object and copy values over from the old one (which it does automatically).
Plan on a little work to understand how you'll fit this into your specific environment and workflow, but I've found the effort to be very worthwhile.

Changing the column order/adding new column for existing table in SQL Server 2008

I have situation where I need to change the order of the columns/adding new columns for existing Table in SQL Server 2008. It is not allowing me to do without drop and recreate. But that is in production system and having data in that table. I can take backup of the data, and drop the existing table and change the order/add new columns and recreate it, insert the backup data into new table.
Is there any best way to do this without dropping and recreating. I think SQL Server 2005 will allow this process without dropping and recreating while changing to existing table structure.
Thanks
You can't really change the column order in a SQL Server 2008 table - it's also largely irrelevant (at least it should be, in the relational model).
With the visual designer in SQL Server Management Studio, as soon as you make too big a change, the only reliable way to do this for SSMS is to re-create the table in the new format, copy the data over, and then drop the old table. There's really nothing you can do about this to change it.
What you can do at all times is add new columns to a table or drop existing columns from a table using SQL DDL statements:
ALTER TABLE dbo.YourTable
ADD NewColumn INT NOT NULL ........
ALTER TABLE dbo.YourTable
DROP COLUMN OldColumn
That'll work, but you won't be able to influence the column order. But again: for your normal operations, column order in a table is totally irrelevant - it's at best a cosmetic issue on your printouts or diagrams..... so why are you so fixated on a specific column order??
There is a way to do it by updating SQL server system table:
1) Connect to SQL server in DAC mode
2) Run queries that will update columns order:
update syscolumns
set colorder = 3
where name='column2'
But this way is not reccomended, because you can destroy something in DB.
One possibility would be to not bother about reordering the columns in the table and simply modify it by add the columns. Then, create a view which has the columns in the order you want -- assuming that the order is truly important. The view can be easily changed to reflect any ordering that you want. Since I can't imagine that the order would be important for programmatic applications, the view should suffice for those manual queries where it might be important.
As the other posters have said, there is no way without re-writing the table (but SSMS will generate scripts which do that for you).
If you are still in design/development, I certainly advise making the column order logical - nothing worse than having a newly added column become part of a multi-column primary key and having it no where near the other columns! But you'll have to re-create the table.
One time I used a 3rd party system which always sorted their columns in alphabetical order. This was great for finding columns in their system, but whenever they revved their software, our procedures and views became invalid. This was in an older version of SQL Server, though. I think since 2000, I haven't seen much problem with incorrect column order. When Access used to link to SQL tables, I believe it locked in the column definitions at time of table linking, which obviously has problems with almost any table definition changes.
I think the simplest way would be re-create the table the way you want it with a different name and then copy the data over from the existing table, drop it, and re-name the new table.
Would it perhaps be possible to script the table with all its data.
Do an edit on the script file in something like notepad++
Thus recreating the table with the new columns but the same.
Just a suggestion, but it might take a while to accomplish this.
Unless you write yourself a small little c# application that can work with the file and apply rules to it.
If only notepadd++ supported a find and move operation

Forcing Management Studio to use ALTER TABLE instead of DROP/CREATE

I'm wondering if is there a way to force MSSQL Management Studio to produce a script like this:
ALTER TABLE Mytable
ADD MyCol bit NOT NULL
CONSTRAINT MyColDefault
DEFAULT 0 WITH VALUES
ALTER TABLE [dbo].Mytable
ALTER COLUMN MyCol2 int NULL
GO
when I alter a very simple property of a column on a table.
If I do this in the designer and ask for the produced script, the script doesn't do such simple tasks, but instead copies all the data in a tmp table, drops the original table, renames the tmp table with the original table name. And, of course, drops and recreates every constraint and relationships.
Is there any option I can change to change this behaviour? Or, this may be possible, is there some danger I don't see in using the simple ALTER TABLE above?
thanks.
Yes you can!
In SQL Server Management Studio, go into the table design mode for the table in question, and make your changes. However: do not click on the "Save" button, but instead right-click in the table design view, there should be a "Generate Change Script" item at the end of your context menu.
Click on that menu item and you'll get presented a pop-up dialog box which contains the T-SQL script needed to do those changes that you made to the table in the designer. Copy or save that T-SQL code, and cancel out of the designer, and voila - you have your change script!
UPDATE: Marco, sorry, I don't think there's any option to change the default behavior, at least not right now. You might want to file an enhancement request with Microsoft on Microsoft Connect to propose that - good idea, I would think!
You can't change the behaviour, it's just that the default script it creates is not always the most efficient. It creates scripts in a format it knows will work, although frequently the results will be slow and resource-heavy. I recommend you get used to creating the script for all changes yourself as you can better optimize it. There's nothing wrong with what you've created (providing you have no existing constraints/dependencies on MyCol2 that would be invalidated by it becoming a nullable int)
Just to augment #marc_s's answer. In case you still can't generate the change script 'cause your table needs to be recreated, you need to go to Tools -> Options and under Designers -> Table and Database Designers unmark the option Prevent saving changes that require table re-creation.
easy! just go to Tool->Option, then the Designer node and select Table and Database designer so that you can uncheck the Prevent saving changes that require ... checkbox.
Now you can make any chage on your tables design!

Resources