Common SQL and T-SQL statements (1)

Source: Internet
Author: User
1. sort by strokes of the Last Name:
Select * From TableName Order By CustomerName Collate Chinese_PRC_Stroke_ci_as
2. database encryption:
Select encrypt ('original password ')
Select pwdencrypt ('original password ')
Select pwdcompare ('original password', 'encrypted password') = 1 -- same; otherwise, different encrypt ('original password ')
Select pwdencrypt ('original password ')
Select pwdcompare ('original password', 'encrypted password') = 1 -- same; otherwise, different

3. Retrieve the fields in the table:
Declare @ list varchar (1000), @ SQL nvarchar (1000)
Select @ list = @ list + ',' + B. name from sysobjects a, syscolumns B where a. id = B. id and a. name = 'table'
Set @ SQL = 'select' + right (@ list, len (@ list)-1) + 'from table'
Exec (@ SQL)

4. View hard disk partitions:
EXEC master .. xp_fixeddrives

5. Compare whether tables A and B are equal:
If (select checksum_agg (binary_checksum (*) from)
=
(Select checksum_sum( binary_checksum (*) from B)
Print 'Equality'
Else
Print 'unequal'

6. Kill all event Inspector processes:
DECLARE hcforeach cursor global for select 'Kill '+ RTRIM (spid) FROM master. dbo. sysprocesses
WHERE program_name IN ('SQL filer', n' SQL event profiler ')
EXEC sp_msforeach_worker '? '

7. Record Search:
Starting with N records
Select Top N * From table
-------------------------------
N to M records (primary index ID required)
Select Top M-N * From table Where ID in (Select Top m id From Table) Order by ID Desc
----------------------------------
N to the end record
Select Top N * From Table Order by ID Desc

8. How to modify the Database Name:
Sp_renamedb 'old _ name', 'new _ name'

9: Get all user tables in the current database
Select Name from sysobjects where xtype = 'U' and status> = 0

10: Get all fields of a table
Select name from syscolumns where id = object_id ('table name ')

11. View views, stored procedures, and functions related to a table
Select a. * from sysobjects a, syscomments B where a. id = B. id and B. text like '% table name %'

12: view all stored procedures in the current database
Select name as stored procedure name from sysobjects where xtype = 'P'

13: Query all databases created by the user
Select * from master .. sysdatabases D where sid not in (select sid from master .. syslogins where name = 'sa ')
Or
Select dbid, name AS DB_NAME from master .. sysdatabases where sid <> 0x01

14: query the fields and Data Types of a table
Select column_name, data_type from information_schema.columns
Where table_name = 'table name'

[N]. [title]:
Select * From TableName Order By CustomerName

[N]. [title]:
Select * From TableName Order By CustomerName

 

1. view the database version
Select @ version

2. view the operating system parameters of the machine where the database is located
Exec master .. xp_msver

3. view database startup parameters
Sp_configure

4. view the database startup time
Select convert (varchar (30), login_time, 120) from master .. sysprocesses where spid = 1

View database server name and Instance name
Print 'server Name ...... + convert (varchar (30), @ SERVERNAME)
Print 'instance ......: '+ convert (varchar (30), @ SERVICENAME)
5. View All Database names and sizes
Sp_helpdb

SQL statement used to rename a database
Sp_renamedb 'old _ dbname', 'new _ dbname'

6. View logon information of all database users
Sp_helplogins

View the role information of all database users
Sp_helpsrvrolemember

Fixed the fix_orphan_user script or LoneUser process that can be used to isolate users during server migration.

Change the user owner of a Data Object
Sp_changeobjectowner [@ objectname =] 'object', [@ newowner =] 'owner'

Note: changing any part of the object name may corrupt the script and stored procedure.

You can use the add_login_to_aserver script to back up the database user logon information on a server.

7. view linked servers
Sp_helplinkedsrvlogin

View remote database user logon information
Sp_helpremotelogin

8. view the size of a data object in a database
Sp_spaceused @ objname

You can also use the sp_toptables process to view the maximum N tables (50 by default ).

View the index information of a data object in a database
Sp_helpindex @ objname

You can also use the SP_NChelpindex process to view more detailed indexes.
SP_NChelpindex @ objname

Clustered indexes sort records in physical order and occupy less space.
We recommend that you use non-clustered indexes and constraints for tables with frequent key value DML operations. The fillfactor parameter uses the default value.
View the constraints of a data object in a database
Sp_helpconstraint @ objname

9. view all stored procedures and functions in the database
Use @ database_name
Sp_stored_procedures
View the source code of stored procedures and functions
Sp_helptext '@ procedure_name'

View the Data Object Name containing a string @ str
Select distinct object_name (id) from syscomments where text like '% @ str %'

Create an encrypted stored procedure or function WITH the with encryption parameter before the

You can use sp_decrypt to decrypt encrypted stored procedures and functions.

10. View user and process information in the database
Sp_who
View information about active users and processes in the SQL Server database
Sp_who 'active'
View the locks in the SQL Server database
Sp_lock

Process No. 1--50 is used internally in the SQL Server system. If the process no. is greater than 50, it is the user's connection process.
Spid is the process number, dbid is the database number, and objid is the data object number
View the SQL statement being executed by the Process
Dbcc inputbuffer ()

We recommend that you use the improved sp_who3 process to directly view the SQL statements run by the process.
Sp_who3

Check the process of using sp_who_lock for deadlocks
Sp_who_lock

11. Methods for shrinking Database Log Files
Shrink database logs in simple recovery mode. The size unit of @ database_name_log after the contraction is M.
Backup log @ database_name with no_log
Dbcc shrinkfile (@ database_name_log, 5)
12. How to analyze SQL Server SQL statements:

Set statistics time... {on | off}
Set statistics io... {on | off}
Display query execution plan in graphical mode

In the query analyzer-> query-> display estimated evaluation plan (D)-Ctrl-L or click the graph in the toolbar

Display query execution plan in text mode
Set showplan_all... {on | off}

Set showplan_text... {on | off}
Set statistics profile... {on | off}

13. When an inconsistency error occurs, the NT Event Viewer displays error 3624. How to fix the database

Comment out the table referenced in the application with an inconsistent error, recover the table on the backup or other machines, and then perform the repair operation.

Alter database [@ error_database_name] set single_user

Fix inconsistent tables

Dbcc checktable ('@ error_table_name', repair_allow_data_loss)

Or, unfortunately, you can fix the name of a small database with an inconsistent error.

Dbcc checkdb ('@ error_database_name', repair_allow_data_loss)
Alter database [@ error_database_name] set multi_user
CHECKDB has three parameters:
Repair_allow_data_loss includes allocating and unassigning rows and pages to correct the allocation error, structure row, or page error,
And delete corrupted text objects. These repairs may cause 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 is completed, back up the database.
Repair_fast Performs small and time-consuming repair operations, such as fixing additional keys in non-clustered indexes.
These repairs can be completed quickly without the risk of data loss.
Repair_rebuild performs all 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.

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.