SQL Server中SELECT (Transact-SQL)语法定义和解释
语法定义:
<SELECT statement> ::=
[ WITH { [ XMLNAMESPACES , ] [ <common_table_expression> [ , ...n ] ] } ]
<query_expression>
[ ORDER BY <order_by_expression> ]
[ <FOR Clause> ]
[ OPTION ( <query_hint> [ , ...n ] ) ]
<query_expression> ::=
{ <query_specification> | ( <query_expression> ) }
[ { UNION [ ALL ] | EXCEPT | INTERSECT }
<query_specification> | ( <query_expression> ) [ ...n ] ]
<query_specification> ::=
SELECT [ ALL | DISTINCT ]
[ TOP ( expression ) [ PERCENT ] [ WITH TIES ] ]
<select_list>
[ INTO new_table ]
[ FROM { <table_source> } [ , ...n ] ]
[ WHERE <search_condition> ]
[ <GROUP BY> ]
[ HAVING <search_condition> ]
[ ; ]
解释:
<SELECT statement>、<query_expression> 、<query_specification>
等,这些用尖括号括起来的,称为术语::=
后面跟随的是对术语的解释- 像这种被中括号括起来的
[ WHERE <search_condition> ] [ <GROUP BY> ] [ HAVING <search_condition> ]
都表示为可选元素 {}
被这种花括号括起来的表示必选元素,如果花括号中有|
这种符号,表示只能选其一,比如这种:{ UNION [ ALL ] | EXCEPT | INTERSECT }
[ ...n ]
表示对前面所写元素的0到多次重复[ , ...n ]
表示对前面所写元素的0到多次重复,用逗号隔开
把上面Select语法拆分成一个最简单的查询语句
上面Select
语法定义是由3个术语组成,分别是:
<query_specification> ::=
SELECT [ ALL | DISTINCT ]
[ TOP ( expression ) [ PERCENT ] [ WITH TIES ] ]
<select_list>
[ INTO new_table ]
[ FROM { <table_source> } [ , ...n ] ]
[ WHERE <search_condition> ]
[ <GROUP BY> ]
[ HAVING <search_condition> ]
[ ; ]
<query_expression> ::=
{ <query_specification> | ( <query_expression> ) }
[ { UNION [ ALL ] | EXCEPT | INTERSECT }
<query_specification> | ( <query_expression> ) [ ...n ] ]
<SELECT statement> ::=
[ WITH { [ XMLNAMESPACES , ] [ <common_table_expression> [ , ...n ] ] } ]
<query_expression>
[ ORDER BY <order_by_expression> ]
[ <FOR Clause> ]
[ OPTION ( <query_hint> [ , ...n ] ) ]
- 对
<query_specification>
进行简化拆解,就只剩
SELECT <select_list>
- 对
<query_expression>
进行简化拆解,就只剩{ <query_specification> | ( <query_expression> ) }
然后选择一个,我们把<query_specification>
带入就是
SELECT <select_list>
- 对
<SELECT statement>
进行简化拆解,就只剩<query_expression>
,然后继续带入,最简查询语句就出来了
SELECT <select_list>
由上面定义我们知道 <select_list>
也是术语,他可以是一个表达式,一个值,等,或者是通过逗号分隔出来的各种表达式。