Use SQL statements to add delete modification fields, basic operations for some tables and fields, database backups, etc.

Source: Internet
Author: User

To add a delete modification field with an SQL statement
1. Add fields
ALTER TABLE DOCDSP add Dspcode char (200)
2. Delete a field
ALTER TABLE table_name DROP COLUMN column_name
3. Modify the field type
ALTER TABLE table_name ALTER COLUMN COLUMN_NAME NEW_DATA_TYPE
4.sp_rename renaming
Changes the name of a user-created object (such as a table, column, or user-defined data type) in the current database.
Grammar
sp_rename [@objname =] ' object_name ',
[@newname =] ' New_name '
[, [@objtype =] ' object_type ']
such as: EXEC sp_rename ' newname ', ' Partstock '
5.sp_help some basic scenarios for displaying tables
Sp_help ' object_name ' such as: EXEC sp_help ' Partstock '
6. Determine whether a field partvelocity exists in a table Partstock
if exists (SELECT * from syscolumns where id=object_id (' Partstock ') and Name= ' partvelocity ')
print ' partvelocity exists '
else print ' partvelocity NOT EXISTS '
Another method:
To determine the existence of a table:
Select COUNT (*) from sysobjects where type= ' U ' and name= ' your table name '
To determine the existence of a field:
Select COUNT (*) from syscolumns
WHERE id = (select id from sysobjects where type= ' u ' and name= ' your table name ')
and name = ' The field name you want to judge '

A small example
--Suppose the table to be processed is named: TB
--Determine if the table in which you want to add a column has a primary key
if exists (select 1 from sysobjects where parent_obj=object_id (' TB ') and xtype= ' PK ')
Begin
There are already primary keys in print ' table and columns can only be added as normal columns '
--Add a column of type int, the default value is 0
ALTER TABLE TB add column name int default 0
End
Else
Begin
No primary key in print ' table, add primary key column '
--Add a column of type int, the default value is 0
ALTER TABLE TB add column name int primary key default 0
End

7. Random reading of several records
Access syntax: SELECT top * FROM table name ORDER by Rnd (ID)
SQL server:select Top n * FROM table name ORDER by NEWID ()
MySQL select * FROM table name Order by rand () Limit n
8. Description: Schedule five minutes advance reminder
Sql:select * from Schedule where DATEDIFF (minute,f start time, GETDATE ()) >5

9. Top 10 Records
Select Top Ten * form table1 where range

10. A result table is derived from all rows in TableA but not in TableB and TableC and all duplicate rows are eliminated
(select a from TableA) except (select a from TableB) except (select a from TableC)

11. Description: Randomly remove 10 data
Select Top * FROM tablename ORDER by NEWID ()

12. List all table names in the database
Select name from sysobjects where type=u
13. List all the field names in the table
Select name from syscolumns where id=object_id (TableName)
14. Description: The type, Vender, and PCs fields are listed in the Type field and case can be conveniently implemented in multiple selections, similar to case in select.
Select Type,sum (Case vender if A then PCs else 0 end), sum (case vender if C then PCs else 0 end), sum (case vender when B Then PCs else 0 end) from the TableName group by type
15. Description: Initialization table table1
TRUNCATE TABLE table1
16. Description: Several advanced query arithmetic words
A:union operator
The UNION operator derives a result table by combining the other two result tables (for example, TABLE1 and TABLE2) and eliminating any duplicate rows in the table. When all is used with the Union (that is, union ALL), duplicate rows are not eliminated. In both cases, each row of the derived table is either from TABLE1 or from TABLE2.

B:except operator
The EXCEPT operator derives a result table by including all rows in TABLE1 but not in TABLE2 and eliminating all duplicate rows. When all is used with EXCEPT (EXCEPT all), duplicate rows are not eliminated.

C:intersect operator
The INTERSECT operator derives a result table by including only rows in TABLE1 and TABLE2 and eliminating all duplicate rows. When all is used with INTERSECT (INTERSECT all), duplicate rows are not eliminated.
Note: Several query result rows that use an operation word must be consistent.


17. Description: Online view query (table name 1:a)
SELECT * FROM (select A,b,c from a) T where t.a > 1;

18. Description: The use of between, between limits the query data range when the boundary value is included, not between does not include
SELECT * FROM table1 where time between time1 and time2
Select A,b,c, from table1 where a is not between value 1 and value 2

19. Description: How to use
SELECT * FROM table1 where a [not] in (' Value 1 ', ' Value 2 ', ' Value 4 ', ' Value 6 ')

20. Description: Two related tables, delete information in the primary table that is not already in the secondary table
Delete from table1 where NOT EXISTS (SELECT * from table2 where table1.field1=table2.field1)
21. Description: Copy table (copy structure only, source table name: A new table name: B) (Access available)
Law one: SELECT * into B from a where 1<>1
Law II: SELECT top 0 * into B from a

22. Description: Copy table (copy data, source table name: A target table name: B) (Access available)
Insert into B (A, B, c) select d,e,f from B;

23. Description: Copy of table across databases (use absolute path for specific data) (Access available)
Insert into B (A, B, c) Select d,e,f from B in ' specific database ' where condition
Example:.. From B in "&server.mappath (". ") & "\data.mdb" & "where".
24. Create a Database
CREATE DATABASE Database-name

25. Description: Delete Database
Drop Database dbname
26. Description: Back up SQL Server
---to create a device that backs up data
Use master
EXEC sp_addumpdevice disk, Testback, C:\mssql7backup\MyNwind_1.dat

---start Backup
BACKUP DATABASE pubs to Testback

27. Description: Create a new table
CREATE TABLE TabName (col1 type1 [NOT NULL] [primary key],col2 type2 [NOT NULL],..)
To create a new table from an existing table:
A:create table tab_new like Tab_old (create new table with old table)
B:create table tab_new as Select Col1,col2 ... from tab_old definition only

28. Description:
Delete new table: Drop table TabName

29. Description:
Add a column: Alter table tabname add column col type
Note: Columns cannot be deleted after they are added. DB2 the column plus the data type can not be changed, the only change is to increase the length of the varchar type.

30. Description:
Add primary key: Alter table TabName Add primary key (COL)
Description
Delete primary key: Alter table tabname drop primary key (COL)

31. Description:
Creating an index: Create [unique] index idxname on tabname (col ...)
Drop INDEX: Idxname
Note: The index is immutable and you must remove the rebuild if you want to change it.

32. Description:
Creating views: Create VIEW viewname AS SELECT statement
Delete view: Drop View ViewName

33. Description: A few simple basic SQL statements
Select: SELECT * FROM table1 where range
Insert: INSERT INTO table1 (field1,field2) VALUES (value1,value2)
Delete: Delete from table1 where range
Updated: Update table1 set field1=value1 where range
Find: SELECT * FROM table1 where field1 like '%value1% '---the syntax of like is very subtle, check the information!
Sort: SELECT * FROM table1 ORDER by FIELD1,FIELD2 [DESC]
Total: SELECT Count * as TotalCount from table1
Sum: Select SUM (field1) as Sumvalue from table1
Average: Select AVG (field1) as Avgvalue from table1
Maximum: Select Max (field1) as MaxValue from table1
Min: select min (field1) as MinValue from table1

34. Database backup:

Use Db_ndmspmasterdb;
GO

DECLARE @path varchar (500)
Set @path = ' D:\NDM_Data\DB_NDMSpMasterdb ' +convert (VARCHAR, GETDATE (), 105) + '. Bak '
Select @path

BACKUP DATABASE Db_ndmspmasterdb

to DISK = @path
With FORMAT,
MEDIANAME = ' z_sqlserverbackups ',
NAME = ' Full Backup of Db_ndmspmasterdb ';
GO

Use SQL statements to add delete modification fields, basic operations for some tables and fields, database backups, etc.

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.