1
如何获得数据库里所有表的名字
2
3
平时我们操作比较多的都是表里的数据,也许突然有一天会需要把所有表的名字都列出来看一看——比如,你的论坛是按每个版块一个表来管理的,这时候你要在首页列出各版块的名字。应该怎么办呢?
4
5
肯定得用SELECT吧……但我们平时使用SELECT操作的数据都是表里的数据,表的名字并不是表的数据,这可怎么办呢?
6
7
你可能会想:“功能强大的SQL Server不会连这么简单的功能都实现不了吧?一定会把所有表的名字存储在某个表里……”注意啦!在这儿我要小小地偷换一下概念了——视图(View)也算是一种“表”,只不过它是由固定查询形成的一种“虚拟表”。
8
9
OK,你猜对啦!由SQL Server管理的每个数据库里都有一个名为sysobjects的视图,它是system级别的,所以它的全限定名是——sys.sysobjects
10
11
你可能又会问:“为什么不是sys.tables而是sys.objects呢?”问的好!因为这张表里存储的可不光是数据库里的表,它存储的是一个数据库中所有的“对象”——杂七杂八包括了表的主键、存储过程、触发器等等,一共是24种——表(Table,确切地说是“用户自定义表”)只是这24种对象中的一种。
12
13
剩下的事情……吼吼……
14
15
执行下面的查询语句,可以得到所有包含在sys.sysobjects视图里的数据
16
17
USE AdventureWorks
18
SELECT *
19
FROM sys.sysobjects
20
GO
21
得出数据后,请注意名为type的列——这一列标明了对象的类型,也就是前面提到的24种。在这里,我用一个表格把它们列出来:
22
23
AF = Aggregate function (CLR)
24
C = CHECK constraint
25
D = DEFAULT (constraint or stand-alone)
26
F = FOREIGN KEY constraint
27
FN = SQL scalar function
28
FS = Assembly (CLR) scalar function
29
FT = Assembly (CLR) table-valued function
30
IF = SQL inline table-valued function
31
IT = Internal table
32
P = SQL stored procedure
33
PC = Assembly (CLR) stored procedure
34
PK = PRIMARY KEY constraint
35
R = Rule (old-style, stand-alone)
36
RF = Replication-filter-procedure
37
S = System base table
38
SN = Synonym
39
SQ = Service queue
40
TA = Assembly (CLR) DML trigger
41
TF = SQL table-valued-function
42
TR = SQL DML trigger
43
U = Table (user-defined)
44
UQ = UNIQUE constraint
45
V = View
46
X = Extended stored procedure
47
48
49
OK,我们要得到名称的表(用户自定义表)就是类型为“U”的对象;而sys.objects的类型为“S”。所以,为了达到我们的最终目的,SQL语句应该是——
50
51
USE AdventureWorks
52
SELECT name
53
FROM sys.sysobjects
54
WHERE type='U'
55
GO
56
57
58
下面我再给出一段用C#实现的代码:
59
60
61
62
//========<水之真谛>========//
63
//====<以人为本,关注民生>====//
64
// http://blog.csdn.net/FantasiaX //
65
using System;
66
using System.Data.SqlClient;
67
68
namespace SqlSample
69
{
70
class Program
71
{
72
static void Main(string[] args)
73
{
74
string connectionString = @"Server=(local); Database=AdventureWorks; User ID=sa; Password=password";
75
SqlConnection connection = new SqlConnection();
76
connection.ConnectionString = connectionString;
77
78
string sqlCommandString = @"USE AdventureWorks SELECT name FROM sys.sysobjects WHERE type='U' ORDER BY name";
79
SqlCommand command = new SqlCommand();
80
command.CommandType = System.Data.CommandType.Text;
81
command.CommandText = sqlCommandString;
82
command.Connection = connection;
83
connection.Open();
84
85
SqlDataReader reader = command.ExecuteReader();
86
while (reader.Read())
87
{
88
Console.WriteLine(reader[@"name"]);
89
}
90
}
91
}
92
}
93
94

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

87

88

89

90

91

92

93

94
