SQL Server practical tips collection page 1/2

Source: Internet
Author: User

This includes prompting pending operations, shrinking databases, compressing databases, transferring databases to new users with existing user permissions, checking backup sets, and restoring databases during installation.
(1) pending operations
When installing the SQL or sp patch, the system prompts that a pending installation operation is required. Restart is often useless. solution:
To HKEY_LOCAL_MACHINE \ SYSTEM \ CurrentControlSet \ Control \ Session Manager
Delete PendingFileRenameOperations
(2) shrinking the database
-- Re-Indexing
DBCC REINDEX
DBCC INDEXDEFRAG
-- Shrink data and logs
DBCC SHRINKDB
DBCC SHRINKFILE
(3) compressing the database
Dbcc shrinkdatabase (dbname)
(4) Transfer the database to a new user with existing User Permissions
Exec sp_change_users_login 'Update _ one', 'newname', 'oldname'
Go
(5) Check the backup set
Restore verifyonly from disk = 'e: \ dvbbs. Bak'
(6) database Restoration
Alter database [dvbbs] SET SINGLE_USER
GO
Dbcc checkdb ('dvbbs ', repair_allow_data_loss) WITH TABLOCK
GO
Alter database [dvbbs] SET MULTI_USER
GO

-- CHECKDB has three parameters:
-- REPAIR_ALLOW_DATA_LOSS
-- Execute all the repairs completed by REPAIR_REBUILD, including allocating and unassigning rows and pages to correct the allocation errors, structure row or page errors, and deleting corrupted text objects. These fixes may cause some data loss. The repair operation can be completed under the user transaction to allow the user to roll back the changes. If the rollback is fixed, the database will still contain errors and the backup should be restored. If an error fix is missing due to the severity of the severity level provided, it will omit any fix that depends on the fix. After the restoration, back up the database.
-- REPAIR_FAST Performs small and time-consuming repair operations, such as fixing the additional keys in non-clustered indexes. These repairs can be completed quickly without the risk of data loss.
-- REPAIR_REBUILD: execute all the repairs completed by REPAIR_FAST, including repairs that require a long period of time (such as re-indexing ). There is no risk of data loss when performing these repairs.
-- Dbcc checkdb ('dvbbs ') with NO_INFOMSGS, PHYSICAL_ONLY
Two Methods for clearing SQL SERVER logs
During usage, we often encounter very large database logs. Here we introduce two solutions ......
Method 1
In general, the contraction of the SQL database does not greatly reduce the size of the database. Its main function is to shrink the log size. This operation should be performed regularly to avoid excessive database logs.
1. Set database mode to simple mode: Open the SQL Enterprise Manager, in the root directory of the console, open Microsoft SQL Server --> SQL Server group --> double-click your Server --> double-click to open the database directory --> select your database name (such as the Forum database) forum) --> then right-click and select Properties --> Select Options --> select "simple" in the fault recovery mode, and click OK to save
2. Right-click the current database to view the shrinking database in all tasks. Generally, the default settings in the database do not need to be adjusted. Click OK directly.
3. After shrinking the database, we recommend that you set your database attributes to the standard mode. The operation method is the same as the first one, because logs are often an important basis for restoring the database in case of exceptions.
Method 2
Copy codeThe Code is as follows:
SET NOCOUNT ON
DECLARE @ LogicalFileName sysname,
@ MaxMinutes INT,
@ NewSize INT

USE tablename -- Name of the database to be operated
SELECT @ LogicalFileName = 'tablename _ log', -- log File Name
@ MaxMinutes = 10, -- Limit on time allowed to wrap log.
@ NewSize = 1 -- the size of the log file you want to set (M)
-- Setup/initialize
DECLARE @ OriginalSize int
SELECT @ OriginalSize = size
FROM sysfiles
WHERE name = @ LogicalFileName
SELECT 'original Size of '+ db_name () + 'Log is' +
CONVERT (VARCHAR (30), @ OriginalSize) + '8 K pages or '+
CONVERT (VARCHAR (30), (@ OriginalSize * 8/1024) + 'mb'
FROM sysfiles
WHERE name = @ LogicalFileName
Create table DummyTrans
(DummyColumn char (8000) not null)

DECLARE @ Counter INT,
@ StartTime DATETIME,
@ TruncLog VARCHAR (255)
SELECT @ StartTime = GETDATE (),
@ TruncLog = 'backup log' + db_name () + 'WITH TRUNCATE_ONLY'
Dbcc shrinkfile (@ LogicalFileName, @ NewSize)
EXEC (@ TruncLog)
-- Wrap the log if necessary.
WHILE @ MaxMinutes> DATEDIFF (mi, @ StartTime, GETDATE () -- time has not expired
AND @ OriginalSize = (SELECT size FROM sysfiles WHERE name = @ LogicalFileName)
AND (@ OriginalSize * 8/1024)> @ NewSize
BEGIN -- Outer loop.
SELECT @ Counter = 0
WHILE (@ Counter <@ OriginalSize/16) AND (@ counter< 50000 ))
BEGIN -- update
INSERT DummyTrans VALUES ('fill log ')
DELETE DummyTrans
SELECT @ Counter = @ Counter + 1
END
EXEC (@ TruncLog)
END
SELECT 'final Size of '+ db_name () + 'Log is' +
CONVERT (VARCHAR (30), size) + '8 K pages or '+
CONVERT (VARCHAR (30), (size * 8/1024) + 'mb'
FROM sysfiles
WHERE name = @ LogicalFileName
Drop table DummyTrans
SET NOCOUNT OFF

Several Methods for deleting duplicate data in a database
During database usage, due to program problems, duplicate data may occur, which leads to incorrect database settings ......
Method 1
Declare @ max integer, @ id integer
Declare cur_rows cursor local for select Main field, count (*) from table name group by main field having count (*)> 1
Open cur_rows
Fetch cur_rows into @ id, @ max
While @ fetch_status = 0
Begin
Select @ max = @ max-1
Set rowcount @ max
Delete from table name where primary field = @ id
Fetch cur_rows into @ id, @ max
End
Close cur_rows
Set rowcount 0
Method 2
There are two Repeated Records. One is a completely repeated record, that is, records with all fields being repeated, and the other is records with duplicate key fields, such as duplicate Name fields, other fields are not necessarily repeated or can be ignored.
1. For the first type of repetition, it is easier to solve.
Select distinct * from tableName
You can get the result set without repeated records.
If the table needs to delete duplicate records (one record is retained), you can delete the record as follows:
Select distinct * into # Tmp from tableName
Drop table tableName
Select * into tableName from # Tmp
Drop table # Tmp
The reason for this repetition is that the table design is not weekly. You can add a unique index column.
2. Repeat problems usually require that the first record in the repeat record be retained. The procedure is as follows:
Assume that the duplicate fields are Name and Address. You must obtain the unique result set of the two fields.
Select identity (int, 1, 1) as autoID, * into # Tmp from tableName
Select min (autoID) as autoID into # Tmp2 from # Tmp group by Name, autoID
Select * from # Tmp where autoID in (select autoID from # tmp2)
The last select command gets the result set with no duplicate Name and Address (but an autoID field is added, which can be omitted in the select clause when writing)

Two Methods for changing the user of a table in the database
You may often encounter a problem where all the tables cannot be opened due to the result of restoring a database backup to another machine. The reason is that the current database user was used during table creation ......

-- Change a table
Exec sp_changeobjectowner 'tablename', 'dbo'

-- Store and change all tables
Create procedure dbo. User_ChangeObjectOwnerBatch
@ OldOwner as NVARCHAR (128 ),
@ NewOwner as NVARCHAR (128)
AS
DECLARE @ Name as NVARCHAR (128)
DECLARE @ Owner as NVARCHAR (128)
DECLARE @ OwnerName as NVARCHAR (128)
DECLARE curObject CURSOR
Select 'name' = Name,
'Owner' = user_name (uid)
From sysobjects
Where user_name (uid) = @ OldOwner
Order by name
OPEN curObject
Fetch next from curObject INTO @ Name, @ Owner
WHILE (@ FETCH_STATUS = 0)
BEGIN
If @ Owner = @ OldOwner
Begin
Set @ OwnerName = @ OldOwner + '.' + rtrim (@ Name)
Exec sp_changeobjectowner @ OwnerName, @ NewOwner
End
-- Select @ name, @ NewOwner, @ OldOwner
Fetch next from curObject INTO @ Name, @ Owner
END
Close curObject
Deallocate curObject

GO

Write Data cyclically in SQL SERVER
There's nothing to say. You can see it for yourself. Sometimes it's useful.
Declare @ I int
Set @ I = 1
While @ I <30
Begin
Insert into test (userid) values (@ I)
Set @ I = @ I + 1
End

Two Methods for restoring a database without a Database Log File
Accidental deletion of database log files or other causes of Database Log damage

Method 1
1. Create a database with the same name
2. Stop SQL server again (do not detach the database)
3. overwrite the new database with the data file of the original database.
4. Restart SQL server.
5. When you open the Enterprise Manager, there will be a doubt. Ignore it and execute the following statement (note that you must modify the database name)
6. After completion, You can generally access the data in the database. At this time, the database itself usually needs problems. The solution is to use
The database script creates a new database and imports the data.
USE MASTER
GO
SP_CONFIGURE 'Allow updates', 1 RECONFIGURE WITH OVERRIDE
GO
Update sysdatabases set status = 32768 where name = 'suspicious database name'
Go
Sp_dboption 'questionable database name', 'single user', 'true'
Go
Dbcc checkdb ('questionable database name ')
Go
Update sysdatabases set status = 28 where name = 'questionable database name'
Go
Sp_configure 'Allow updates', 0 reconfigure with override
Go
Sp_dboption 'questionable database name', 'single user', 'false'
Go
Method 2
Cause
Yesterday, the system administrator told me that the disk space of an internal application database is insufficient. I noticed that the database Event Log File XXX_Data.ldf has grown to 3 GB, so I decided to narrow down the log file. After failing to contract the database, I made the biggest and most stupid mistake since I entered the industry: I accidentally deleted this log file! Later, I saw all the articles about database Restoration: "It is critical to ensure the existence of database log files no matter what the situation is ", microsoft even has an article in KB about how to restore a database only by using log files. I really don't know what I thought at that time ?!
This is broken! The database cannot be connected, and the enterprise manager says "(doubt)" next to it )". And the most terrible thing is that this database has never been backed up. The only thing I can find is another database server that was migrated six months ago. The application is usable, but many records, tables, and stored procedures are missing. I really hope this is just a nightmare!
Ineffective recovery steps
Additional database
_ Rambo: when there is no activity log in the deleted log file, you can restore it as follows:
1. to detach a suspicious database, use sp_detach_db.
2. Add a database. You can use sp_attach_single_file_db.
However, it is a pity that after execution, SQL Server will question the inconsistency between the data file and the log file, so it is impossible to attach the database data file.
DTS data export
No. The XXX database cannot be read. DTS Wizard reports "An error occurred in the initialization context ".
Emergency Mode
When Yi Hongyi says there is no log for restoration, you can do this:
1. Set the database to emergency mode.
2. Create a New log file.
3. Restart SQL Server.
4. Set the application database to single-user mode.
5. Perform DBCC CHECKDB
6. If there is no major problem, you can change the database status back. Remember to disable the system table modification option.


I tried to remove the data file of the application database, re-create a database XXX with the same name, stop the SQL service, and overwrite the original data file. Then, follow the steps in yihongyi.
However, it is also a pity that, apart from step 1, other steps are very successful. Unfortunately, after restarting SQL Server, this application database is still in doubt!
However, I am glad that, after doing so, I can Select the data and let me breathe a sigh of relief. However, when the component uses the database, the report says, "an error occurs:-2147467259, failed to run begin transaction in database 'xxx' because the database is in avoidance recovery mode ."


All steps for successful recovery
Set the database to emergency mode
Stop the SQL Server service;
Remove the data file XXX_Data.mdf of the application database;
Re-create a database XXX with the same name;
Stop the SQL service;
Overwrite the original data file;
Run the following statement to set the database to emergency mode;
Run "Use Master"
Go
Sp_configure 'Allow updates', 1
Reconfigure with override
Go"
Execution result:
DBCC execution is complete. If DBCC outputs an error message, contact the system administrator.
The configuration option 'allowupdates' has been changed from 0 to 1. Run the RECONFIGURE statement for installation.


Then run "update sysdatabases set status = 32768 where name = 'xxx '"
Execution result:
(The number of affected rows is 1)


Restart the SQL Server service;
Run the following statement to set the application database to Single User mode;
Run "sp_dboption 'xxx', 'single user', 'true '"
Execution result:
The command is successfully completed.


Ü perform dbcc checkdb;
Run "dbcc checkdb ('xxx ')"
Execution result:
The DBCC result of 'xxx.
The DBCC result of 'sysobjects.
The object 'sysobjects' has 273 rows on 5 pages.
The DBCC result of 'sysindexes.
The object 'sysindexes' has 202 rows, which are on 7 pages.
The DBCC result of 'syscolumns.
.........

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.