search
HomeDatabaseMysql TutorialSQLServer基础语法实例应用(一)

SQLServer基础语法实例应用(一)

Jun 07, 2016 pm 02:53 PM
sqlserverBaseExampleapplicationgrammar

一、基础1、说明:创建数据库 ? 1 CREATE DATABASE database-name 2、说明:删除数据库 ? 1 DROP DATABASE database-name 3、说明:备份数据库 ? 1 2 3 4 5 USE master -- 创建 备份数据的 device EXEC sp_addumpdevice 'disk', 'cc_jz', 'd:cc_jz.dat' --

一、基础 1、说明:创建数据库

?

1

CREATE DATABASE database-name

2、说明:删除数据库

?

1

DROP  DATABASE database-name 

3、说明:备份数据库

?

1

2

3

4

5

USE master

-- 创建 备份数据的 device

EXEC sp_addumpdevice 'disk', 'cc_jz', 'd:cc_jz.dat'

-- 开始 备份

BACKUP DATABASE cc_jz TO cc_jz

4、说明:创建新表

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

create table tabname(col1 type1 [not null] [primary key],col2 type2 [not null],..)

 

--> 测试数据:[a]

if object_id('[a]') is not null drop table [a]

go

create table [a]([ID] int,[品名] varchar(6),[入库数量] int,[入库时间] datetime)

insert [a]

select 1,'矿泉水',100,'2013-01-02' union all

select 2,'方便面',60,'2013-01-03' union all

select 3,'方便面',50,'2013-01-03' union all

select 4,'矿泉水',80,'2013-01-04' union all

select 5,'方便面',50,'2013-01-05'

 

select * from a

/*

ID          品名     入库数量        入库时间

----------- ------ ----------- -----------------------

1           矿泉水    100         2013-01-02 00:00:00.000

2           方便面    60          2013-01-03 00:00:00.000

3           方便面    50          2013-01-03 00:00:00.000

4           矿泉水    80          2013-01-04 00:00:00.000

5           方便面    50          2013-01-05 00:00:00.000

 

(5 行受影响)

 

*/

5、说明:删除新表

?

1

drop table tabname

6、说明:增加一个列

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

Alter table tabname add column col type

 

Alter table a add  col int

 

select * from a

/*

ID          品名     入库数量        入库时间                    col

----------- ------ ----------- ----------------------- -----------

1           矿泉水    100         2013-01-02 00:00:00.000 NULL

2           方便面    60          2013-01-03 00:00:00.000 NULL

3           方便面    50          2013-01-03 00:00:00.000 NULL

4           矿泉水    80          2013-01-04 00:00:00.000 NULL

5           方便面    50          2013-01-05 00:00:00.000 NULL

 

(5 行受影响)

 

*/

7、说明:添加主键:

?

1

Alter table tabname add primary key(col)

说明:删除主键:

?

1

Alter table tabname drop primary key(col)

8、说明:创建索引:

?

1

create [unique] index idxname on tabname(col….)

删除索引:

?

1

drop index idxname

注:索引是不可更改的,想更改必须删除重新建。

9、说明:创建视图:

?

1

create view viewname as select statement

删除视图:

?

1

drop view viewname

10、说明:几个简单的基本的sql语句

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

--选择:

select * from table1

--插入:

insert into table1(field1,field2) values(value1,value2)

--删除:

delete from table1 --where 范围

--更新:

update table1 set field1=value1 --where 范围

--查找:

select * from table1 where field1 like '%value1%'

--排序:

select * from table1 order by field1,field2 [desc]

--总数:

select count as totalcount from table1

--求和:

select sum(field1) as sumvalue from table1

--平均:

select avg(field1) as avgvalue from table1

--最大:

select max(field1) as maxvalue from table1

--最小:

select min(field1) as minvalue from table1

11、说明:几个高级查询运算词

A: UNION/UNION ALL 运算符

UNION 运算符通过组合其他两个结果表(例如 TABLE1 和 TABLE2)并消去表中任何重复行而派生出一个结果表。

当 ALL 随 UNION 一起使用时(即 UNION ALL),不消除重复行。两种情况下,派生表的每一行不是来自 TABLE1 就是来自 TABLE2。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

--> 测试数据:[a]

if object_id('[a]') is not null drop table [a]

go

create table [a]([ID] int)

insert [a]

select 1 union all

select 1 union all

select 2 union all

select 3 union all

select null

select * from a

/*

 

(5 行受影响)

ID

-----------

1

1

2

3

NULL

 

(5 行受影响)

*/

 

--> 测试数据:[b]

if object_id('[b]') is not null drop table [b]

go

create table [b]([ID] int)

insert [b]

select 1 union all

select 2 union all

select 2 union all

select 4 union all

select null

select * from b

/*

 

(5 行受影响)

ID

-----------

1

2

2

4

NULL

 

(5 行受影响)

 

*/

--合并去重

select * from a

union

select * from b

/*

ID

-----------

NULL

1

2

3

4

 

(5 行受影响)

*/

 

--合并不去重

select * from a

union all

select * from b

/*

ID

-----------

1

1

2

3

NULL

1

2

2

4

NULL

 

(10 行受影响)

*/

B: EXCEPT 运算符

EXCEPT 运算符通过包括所有在 TABLE1 中但不在 TABLE2 中的行并消除所有重复行而派生出一个结果表。

注意:根本没有EXCEPT ALL 的用法;网上很多文章里写有EXCEPT ALL ,实际上是错误的。(测试SQL Server 2000 2005 2008R2 2012都不好用)

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

--> 测试数据:[a]

if object_id('[a]') is not null drop table [a]

go

create table [a]([ID] int)

insert [a]

select 1 union all

select 1 union all

select 2 union all

select 3 union all

select null

select * from a

/*

 

(5 行受影响)

ID

-----------

1

1

2

3

NULL

 

(5 行受影响)

*/

 

--> 测试数据:[b]

if object_id('[b]') is not null drop table [b]

go

create table [b]([ID] int)

insert [b]

select 1 union all

select 2 union all

select 2 union all

select 4 union all

select null

select * from b

/*

 

(5 行受影响)

ID

-----------

1

2

2

4

NULL

 

(5 行受影响)

 

*/

--取两表不同数据并去重

select * from a

EXCEPT

select * from b

/*

ID

-----------

3

 

(1 行受影响)

*/ 

C: INTERSECT 运算符

INTERSECT 运算符通过只包括 TABLE1 和 TABLE2 中都有的行并消除所有重复行而派生出一个结果表。

注意:根本没有INTERSECT ALL 的用法;网上很多文章里写有INTERSECT ALL ,实际上是错误的。(测试SQL Server 2000 2005 2008R2 2012都不好用)

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

--> 测试数据:[a]

if object_id('[a]') is not null drop table [a]

go

create table [a]([ID] int)

insert [a]

select 1 union all

select 1 union all

select 2 union all

select 3 union all

select null

select * from a

/*

 

(5 行受影响)

ID

-----------

1

1

2

3

NULL

 

(5 行受影响)

*/

 

--> 测试数据:[b]

if object_id('[b]') is not null drop table [b]

go

create table [b]([ID] int)

insert [b]

select 1 union all

select 2 union all

select 2 union all

select 4 union all

select null

select * from b

/*

 

(5 行受影响)

ID

-----------

1

2

2

4

NULL

 

(5 行受影响)

 

*/

--取两表相同数据并去重

select * from a

INTERSECT 

select * from b

/*

ID

-----------

NULL

1

2

 

(3 行受影响)

*/ 

12、说明:使用外连接
A、left (outer) join:
左外连接(左连接):结果集几包括连接表的匹配行,也包括左连接表的所有行。

SQL: select a.a, a.b, a.c, b.c, b.d, b.f from a LEFT OUT JOIN b ON a.a = b.c

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

--> 测试数据:[a]

if object_id('[a]') is not null drop table [a]

go

create table [a]([ID] int)

insert [a]

select 1 union all

select 1 union all

select 2 union all

select 3 union all

select null

select * from a

/*

 

(5 行受影响)

ID

-----------

1

1

2

3

NULL

 

(5 行受影响)

*/

 

--> 测试数据:[b]

if object_id('[b]') is not null drop table [b]

go

create table [b]([ID] int)

insert [b]

select 1 union all

select 2 union all

select 2 union all

select 4 union all

select null

select * from b

/*

 

(5 行受影响)

ID

-----------

1

2

2

4

NULL

 

(5 行受影响)

 

*/

 

 

select a.*,b.* from a  a LEFT  JOIN b b ON a.id= b.id

/*

ID          ID

----------- -----------

1           1

1           1

2           2

2           2

3           NULL

NULL        NULL

 

(6 行受影响)

 

*/

B:right (outer) join:

右外连接(右连接):结果集既包括连接表的匹配连接行,也包括右连接表的所有行。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

--> 测试数据:[a]

if object_id('[a]') is not null drop table [a]

go

create table [a]([ID] int)

insert [a]

select 1 union all

select 1 union all

select 2 union all

select 3 union all

select null

select * from a

/*

 

(5 行受影响)

ID

-----------

1

1

2

3

NULL

 

(5 行受影响)

*/

 

--> 测试数据:[b]

if object_id('[b]') is not null drop table [b]

go

create table [b]([ID] int)

insert [b]

select 1 union all

select 2 union all

select 2 union all

select 4 union all

select null

select * from b

/*

 

(5 行受影响)

ID

-----------

1

2

2

4

NULL

 

(5 行受影响)

 

*/

 

 

select a.*,b.* from a  a RIGHT  JOIN b b ON a.id= b.id

/*

ID          ID

----------- -----------

1           1

1           1

2           2

2           2

NULL        4

NULL        NULL

 

(6 行受影响)

 

 

*/

C:full/cross (outer) join:

全外连接:不仅包括符号连接表的匹配行,还包括两个连接表中的所有记录。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

--> 测试数据:[a]

if object_id('[a]') is not null drop table [a]

go

create table [a]([ID] int)

insert [a]

select 1 union all

select 1 union all

select 2 union all

select 3 union all

select null

select * from a

/*

 

(5 行受影响)

ID

-----------

1

1

2

3

NULL

 

(5 行受影响)

*/

 

--> 测试数据:[b]

if object_id('[b]') is not null drop table [b]

go

create table [b]([ID] int)

insert [b]

select 1 union all

select 2 union all

select 2 union all

select 4 union all

select null

select * from b

/*

 

(5 行受影响)

ID

-----------

1

2

2

4

NULL

 

(5 行受影响)

 

*/

 

select a.*,b.* from a  a FULL  JOIN b b ON a.id= b.id

/*

ID          ID

----------- -----------

1           1

1           1

2           2

2           2

3           NULL

NULL        NULL

NULL        4

NULL        NULL

 

(8 行受影响)

 

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What Are the Limitations of Using Views in MySQL?What Are the Limitations of Using Views in MySQL?May 14, 2025 am 12:10 AM

MySQLviewshavelimitations:1)Theydon'tsupportallSQLoperations,restrictingdatamanipulationthroughviewswithjoinsorsubqueries.2)Theycanimpactperformance,especiallywithcomplexqueriesorlargedatasets.3)Viewsdon'tstoredata,potentiallyleadingtooutdatedinforma

Securing Your MySQL Database: Adding Users and Granting PrivilegesSecuring Your MySQL Database: Adding Users and Granting PrivilegesMay 14, 2025 am 12:09 AM

ProperusermanagementinMySQLiscrucialforenhancingsecurityandensuringefficientdatabaseoperation.1)UseCREATEUSERtoaddusers,specifyingconnectionsourcewith@'localhost'or@'%'.2)GrantspecificprivilegeswithGRANT,usingleastprivilegeprincipletominimizerisks.3)

What Factors Influence the Number of Triggers I Can Use in MySQL?What Factors Influence the Number of Triggers I Can Use in MySQL?May 14, 2025 am 12:08 AM

MySQLdoesn'timposeahardlimitontriggers,butpracticalfactorsdeterminetheireffectiveuse:1)Serverconfigurationimpactstriggermanagement;2)Complextriggersincreasesystemload;3)Largertablesslowtriggerperformance;4)Highconcurrencycancausetriggercontention;5)M

MySQL: Is it safe to store BLOB?MySQL: Is it safe to store BLOB?May 14, 2025 am 12:07 AM

Yes,it'ssafetostoreBLOBdatainMySQL,butconsiderthesefactors:1)StorageSpace:BLOBscanconsumesignificantspace,potentiallyincreasingcostsandslowingperformance.2)Performance:LargerrowsizesduetoBLOBsmayslowdownqueries.3)BackupandRecovery:Theseprocessescanbe

MySQL: Adding a user through a PHP web interfaceMySQL: Adding a user through a PHP web interfaceMay 14, 2025 am 12:04 AM

Adding MySQL users through the PHP web interface can use MySQLi extensions. The steps are as follows: 1. Connect to the MySQL database and use the MySQLi extension. 2. Create a user, use the CREATEUSER statement, and use the PASSWORD() function to encrypt the password. 3. Prevent SQL injection and use the mysqli_real_escape_string() function to process user input. 4. Assign permissions to new users and use the GRANT statement.

MySQL: BLOB and other no-sql storage, what are the differences?MySQL: BLOB and other no-sql storage, what are the differences?May 13, 2025 am 12:14 AM

MySQL'sBLOBissuitableforstoringbinarydatawithinarelationaldatabase,whileNoSQLoptionslikeMongoDB,Redis,andCassandraofferflexible,scalablesolutionsforunstructureddata.BLOBissimplerbutcanslowdownperformancewithlargedata;NoSQLprovidesbetterscalabilityand

MySQL Add User: Syntax, Options, and Security Best PracticesMySQL Add User: Syntax, Options, and Security Best PracticesMay 13, 2025 am 12:12 AM

ToaddauserinMySQL,use:CREATEUSER'username'@'host'IDENTIFIEDBY'password';Here'showtodoitsecurely:1)Choosethehostcarefullytocontrolaccess.2)SetresourcelimitswithoptionslikeMAX_QUERIES_PER_HOUR.3)Usestrong,uniquepasswords.4)EnforceSSL/TLSconnectionswith

MySQL: How to avoid String Data Types common mistakes?MySQL: How to avoid String Data Types common mistakes?May 13, 2025 am 12:09 AM

ToavoidcommonmistakeswithstringdatatypesinMySQL,understandstringtypenuances,choosetherighttype,andmanageencodingandcollationsettingseffectively.1)UseCHARforfixed-lengthstrings,VARCHARforvariable-length,andTEXT/BLOBforlargerdata.2)Setcorrectcharacters

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools