1. Backup the database
BACKUP DATABASE [database_name] TO DISK = '[backup_filename]'
Make sure the MSSQL has access to write to [backup_filename] Continue reading
There are 4 posts filed in Microsoft SQL Server (this is page 1 of 1).
1. Backup the database
BACKUP DATABASE [database_name] TO DISK = '[backup_filename]'
Make sure the MSSQL has access to write to [backup_filename] Continue reading
Here’s how to rebuild indexes:
USE DatabaseName GO EXEC sp_MSforeachtable @command1="print '?' DBCC DBREINDEX ('?', ' ', 80)" GO EXEC sp_updatestats GO
It’s possible but not as easy as ALTER TABLE [table] ADD COLUMN [column] [type] AFTER [anothercolumn]; like supported in MySql.
We need to drop all contraints, create a temporary table with the new structure, copy all data to the temporary table, drop the old table and rename the temporary table.
Below is a script that adds the column newcolumn between place and name in a table named mytable.
ALTER TABLE [mytable] DROP CONSTRAINT [PK_mytable] ALTER TABLE [mytable] DROP CONSTRAINT [DF_mytable_place] ALTER TABLE [mytable] DROP CONSTRAINT [DF_mytable_name] CREATE TABLE tmp_mytable ( [item_id] [int] IDENTITY(1,1) NOT NULL, [place] [int] NOT NULL, [newcolumn] [nvarchar](255) NOT NULL, [name] [nvarchar](255) NOT NULL, CONSTRAINT [PK_mytable] PRIMARY KEY CLUSTERED ( [item_id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] ALTER TABLE [tmp_mytable] ADD CONSTRAINT [DF_mytable_place] DEFAULT ((1)) FOR [place] ALTER TABLE [tmp_mytable] ADD CONSTRAINT [DF_mytable_name] DEFAULT ('') FOR [name] ALTER TABLE [tmp_mytable] ADD CONSTRAINT [DF_mytable_newcolumn] DEFAULT ('newvalue') FOR [newcolumn] SET IDENTITY_INSERT dbo.tmp_mytable ON IF EXISTS(SELECT * FROM [mytable]) EXEC('INSERT INTO [tmp_mytable] (item_id, place, name) SELECT item_id, place, name FROM [mytable] WITH (HOLDLOCK TABLOCKX)') SET IDENTITY_INSERT dbo.tmp_mytable OFF DROP TABLE mytable; EXECUTE sp_rename N'tmp_mytable', N'mytable', 'OBJECT';
If you don’t care about the placement you can add a column to the end of the table using this command:
ALTER TABLE mytable ADD newcolumn [nvarchar](255) NOT NULL CONSTRAINT DF_mytable_newcolumn DEFAULT 'newvalue'
Re-map database user to a login in SQL server after restoring or attaching database
When restoring or attaching a database to a new or different Microsoft SQL server the logins and mappings to the database users are lost. If you create the logins again you’re not able to map the users because they already exist in the database:
User, group, or role '{login}' already exists in the current database.