SELECT (Transact-SQL) Retrieves rows from the database and enables the selection of one or many rows or columns from one or many tables in SQL Server 2012. The full syntax of the SELECT statement is complex, but the main clauses can be summarized as: [ WITH <common_table_expression>] SELECT select_list [ INTO new_table ] [ FROM table_source ] [ WHERE search_condition ] [ GROUP BY group_by_expression ] [ HAVING search_condition ] [ ORDER BY order_expression [ ASC | DESC ] ] The UNION, EXCEPT and INTERSECT operators can be used between queries to combine or compare their results into one result set. Transact-SQL Syntax Conventions

Syntax
<SELECT statement> ::=
[WITH <common_table_expression> [,...n]]
<query_expression>
[ ORDER BY { order_by_expression | column_position [ ASC | DESC ] }
[ ,...n ] ]
[ <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 > ]

Remarks
Because of the complexity of the SELECT statement, detailed syntax elements and arguments are shown by clause: The order of the clauses in the SELECT statement is significant. Any one of the optional clauses can be omitted, but when the optional clauses are used, they must appear in the appropriate order. SELECT statements are permitted in user-defined functions only if the select lists of these statements contain expressions that assign values to variables that are local to the functions. A four-part name constructed with the OPENDATASOURCE function as the server-name part can be used as a table source wherever a table name can appear in a SELECT statement. Some syntax restrictions apply to SELECT statements that involve remote tables. Logical Processing Order of the SELECT statementThe following steps show the logical processing order, or binding order, for a SELECT statement. This order determines when the objects defined in one step are made available to the clauses in subsequent steps. For example, if the query processor can bind to (access) the tables or views defined in the FROM clause, these objects and their columns are made available to all subsequent steps. Conversely, because the SELECT clause is step 8, any column aliases or derived columns defined in that clause cannot be referenced by preceding clauses. However, they can be referenced by subsequent clauses such as the ORDER BY clause. Note that the actual physical execution of the statement is determined by the query processor and the order may vary from this list. FROM ON JOIN WHERE GROUP BY WITH CUBE or WITH ROLLUP HAVING SELECT DISTINCT ORDER BY TOP

Permissions
Selecting data requires SELECT permission on the table or view, which could be inherited from a higher scope such as SELECT permission on the schema or CONTROL permission on the table. Or requires membership in the db_datareader or db_owner fixed database roles, or the sysadmin fixed server role. Creating a new table using SELECT INTO also requires both the CREATE TABLE permission, and the ALTER SCHEMA permission on the schema that owns the new table.

See Also
|
SELECT (Transact-SQL) Recupera filas de la base de datos y habilita la selección de una o varias filas o columnas de una o varias tablas en SQL Server 2012. La sintaxis completa de la instrucción SELECT es compleja, aunque las cláusulas principales se pueden resumir del modo siguiente: [ WITH <common_table_expression>] SELECT select_list [ INTO new_table ] [ FROM table_source ] [ WHERE search_condition ] [ GROUP BY group_by_expression ] [ HAVING search_condition ] [ ORDER BY order_expression [ ASC | DESC ] ] Los operadores UNION, EXCEPT e INTERSECT se pueden utilizar entre consultas para combinar o comparar resultados en un conjunto de resultados. Convenciones de sintaxis de Transact-SQL

Sintaxis
<SELECT statement> ::=
[WITH <common_table_expression> [,...n]]
<query_expression>
[ ORDER BY { order_by_expression | column_position [ ASC | DESC ] }
[ ,...n ] ]
[ <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 > ]

Comentarios
Debido a la complejidad de la instrucción SELECT, se muestran elementos y argumentos detallados de la sintaxis de cada cláusula: El orden de las cláusulas en la instrucción SELECT es importante. Se puede omitir cualquiera de las cláusulas opcionales pero, cuando se utilizan, deben aparecer en el orden apropiado. Las instrucciones SELECT se permiten en las funciones definidas por el usuario solo si las listas de selección de estas instrucciones contienen expresiones que asignan valores a variables locales de las funciones. Un nombre de cuatro partes creado con la función OPENDATASOURCE como la parte de nombre de servidor se puede utilizar como origen de tabla en todos los lugares de las instrucciones SELECT donde pueda aparecer un nombre de tabla. Existen algunas restricciones sintácticas en las instrucciones SELECT relacionadas con las tablas remotas. Orden de procesamiento lógico de la instrucción SELECTLos pasos siguientes muestran el orden de procesamiento lógico, u orden de enlaces, de una instrucción SELECT. Este orden determina cuándo los objetos definidos en un paso están disponibles para las cláusulas en pasos posteriores. Por ejemplo, si el procesador de consultas puede enlazar (obtener acceso) a las tablas o las vistas definidas en la cláusula FROM, estos objetos y sus columnas están disponibles para todos los pasos siguientes. Por el contrario, dado que la cláusula SELECT es el paso 8, las cláusulas anteriores no pueden hacer referencia a los alias de columna o columnas derivadas definidas en esa cláusula. Sin embargo, las cláusulas siguientes, tales como la cláusula ORDER BY, sí pueden hacer referencia. Observe que la ejecución física real de la instrucción está determinada por el procesador de consultas y el orden puede variar en esta lista. FROM ON JOIN WHERE GROUP BY WITH CUBE o WITH ROLLUP HAVING SELECT DISTINCT ORDER BY TOP

Permisos
La selección de datos necesita el permiso SELECT en la tabla o en la vista, que se puede heredar de un ámbito superior como el permiso SELECT en el esquema o el permiso CONTROL en la tabla. O bien, se necesita pertenecer a los roles fijos de base de datos db_datareader o db_owner, o al rol fijo de servidor sysadmin. La creación de una nueva tabla mediante SELECT INTO también necesita tanto el permiso CREATE TABLE como el permiso ALTER SCHEMA en el esquema al que pertenece la nueva tabla.

Vea también
|