Вирази (Transact-SQL) - SQL Server

  1. синтаксис Syntax
  2. аргументи Arguments
  3. Результати вираження Expression Results
  4. Див. Також: See Also

ОБЛАСТЬ ЗАСТОСУВАННЯ: ОБЛАСТЬ ЗАСТОСУВАННЯ:   SQL Server   База даних SQL Azure   Сховище даних SQL Azure   Parallel Data Warehouse APPLIES TO:   SQL Server   Azure SQL Database   Azure SQL Data Warehouse   Parallel Data Warehouse   Поєднання символів і операторів, що використовується компонентом Компонент SQL Server Database Engine SQL Server Database Engine для обчислення одиночного значення даних SQL Server База даних SQL Azure Сховище даних SQL Azure Parallel Data Warehouse APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel Data Warehouse

Поєднання символів і операторів, що використовується компонентом Компонент SQL Server Database Engine SQL Server Database Engine для обчислення одиночного значення даних. Is a combination of symbols and operators that the Компонент SQL Server Database Engine SQL Server Database Engine evaluates to obtain a single data value. Окремі константи, змінні, стовпці і скалярні функції є прикладами простих виразів. Simple expressions can be a single constant, variable, column, or scalar function. Для з'єднання двох і більш простих виразів в одне складне можна використовувати оператори. Operators can be used to join two or more simple expressions into a complex expression.

Синтаксичні позначення в Transact-SQL   Transact-SQL Syntax Conventions Синтаксичні позначення в Transact-SQL Transact-SQL Syntax Conventions

синтаксис Syntax

- Syntax for SQL Server and Azure SQL Database {constant | scalar_function | [Table_name. ] Column | variable | (Expression) | (Scalar_subquery) | {Unary_operator} expression | expression {binary_operator} expression | ranking_windowed_function | aggregate_windowed_function} - Syntax for Azure SQL Data Warehouse and Parallel Data Warehouse - Expression in a SELECT statement <expression> :: = {constant | scalar_function | column | variable | (Expression) | {Unary_operator} expression | expression {binary_operator} expression} [COLLATE Windows_collation_name] - Scalar Expression in a DECLARE, SET, IF ... ELSE, or WHILE statement <scalar_expression> :: = {constant | scalar_function | variable | (Expression) | (Scalar_subquery) | {Unary_operator} expression | expression {binary_operator} expression} [COLLATE {Windows_collation_name]

аргументи Arguments

Термін Term Визначення Definition constant constant Символ, який представляє одне конкретне значення даних. Is a symbol that represents a single, specific data value. Додаткові відомості див. У статті Константи (Transact-SQL) . For more information, see Constants (Transact-SQL) . scalar_function scalar_function Одиниця синтаксису Transact-SQL Transact-SQL, який надає певну службу і повертає одиночне значення. Is a unit of Transact-SQL Transact-SQL syntax that provides a specific service and returns a single value. scalar_function може бути вбудованою скалярною функцією, такий як SUM, GETDATE або CAST, або обумовленими користувачем скалярними функціями. scalar_function can be built-in scalar functions, such as the SUM, GETDATE, or CAST functions, or scalar user-defined functions. [Table_name. [Table_name. ]] Ім'я або псевдонім таблиці. Is the name or alias of a table. column column Ім'я стовпця. Is the name of a column. Тільки ім'я стовпця використовується у виразі. Only the name of the column is allowed in an expression. variable variable Ім'я змінної або параметр. Is the name of a variable, or parameter. Додаткові відомості див. У статті DECLARE @local_variable (Transact-SQL) . For more information, see DECLARE @local_variable (Transact-SQL) . (Expression) (expression) Будь-яке допустиме вираз з визначених у цьому розділі. Is any valid expression as defined in this topic. Дужки є операторами угруповання, що гарантують, що всі оператори вираження всередині дужок будуть виконані, перш ніж результуючий вираз буде об'єднано з іншим. The parentheses are grouping operators that make sure that all the operators in the expression within the parentheses are evaluated before the resulting expression is combined with another. (Scalar_subquery) (scalar_subquery) Вкладений запит, який повертає одиночне значення. Is a subquery that returns one value. Приклад: For example:
SELECT MAX (UnitPrice)
FROM Products {unary_operator} {unary_operator} Унарні оператори можна застосовувати тільки до виразів, виконуваних з будь-якими типами даних з категорії числових типів даних. Unary operators can be applied only to expressions that evaluate to any one of the data types of the numeric data type category. Оператор, який має тільки один числовий операнд: Is an operator that has only one numeric operand:
+ Позначає позитивне число. + Indicates a positive number.
- позначає негативне число. - indicates a negative number.
~ Позначає оператор доповнення. ~ Indicates the one's complement operator. {Binary_operator} {binary_operator} Цей оператор вказує, як об'єднуються два вирази для отримання єдиного результату. Is an operator that defines the way two expressions are combined to yield a single result. Аргумент binary_operator може бути арифметичним, логічним, двійкового або унарним оператором, а також оператором присвоєння (=), порівняння або об'єднання (+). binary_operator can be an arithmetic operator, the assignment operator (=), a bitwise operator, a comparison operator, a logical operator, the string concatenation operator (+), or a unary operator. Додаткові відомості про операторів см. в розділі Оператори (Transact-SQL). For more information about operators, see Operators (Transact-SQL) . ranking_windowed_function ranking_windowed_function Будь-яка ранжирує функція мови Transact-SQL Transact-SQL. Is any Transact-SQL Transact-SQL ranking function. Додаткові відомості див. У розділі Ранжирующие функції (Transact-SQL) . For more information, see Ranking Functions (Transact-SQL) . aggregate_windowed_function aggregate_windowed_function Будь-яка агрегатна функція мови Transact-SQL Transact-SQL, що містить пропозицію OVER. Is any Transact-SQL Transact-SQL aggregate function with the OVER clause. Додаткові відомості див. У статті Пропозиція OVER (Transact-SQL) . For more information, see OVER Clause (Transact-SQL) .

Результати вираження Expression Results

Для простих виразів, що складаються з однієї константи, змінної, скалярної функції або імені стовпця, як тип даних, параметрів сортування, числа розрядів, точності і значення виразу використовуються тип даних, параметри сортування, число розрядів, точність і значення елемента, на який вони посилаються. For a simple expression made up of a single constant, variable, scalar function, or column name: the data type, collation, precision, scale, and value of the expression is the data type, collation, precision, scale, and value of the referenced element.

При об'єднанні двох виразів за допомогою операторів порівняння або логічних операторів результат буде мати логічний тип даних і може приймати одне з наступних значень: TRUE, FALSE або UNKNOWN. When two expressions are combined by using comparison or logical operators, the resulting data type is Boolean and the value is one of the following: TRUE, FALSE, or UNKNOWN. Додаткові відомості про логічні типи даних див. Розділ Оператори порівняння (Transact-SQL) . For more information about Boolean data types, see Comparison Operators (Transact-SQL) .

При об'єднанні двох виразів за допомогою арифметичних, побітових або строкових операторів тип даних результату визначається використовуваним оператором. When two expressions are combined by using arithmetic, bitwise, or string operators, the operator determines the resulting data type.

Складні вирази, складені з декількох символів і операторів, обчислюються в поодинокі результати. Complex expressions made up of many symbols and operators evaluate to a single-valued result. Тип даних, параметри сортування, точність і значення результуючого виразу визначаються об'єднанням складових виразів (по два за один раз) до тих пір, поки не буде отримано кінцевий результат. The data type, collation, precision, and value of the resulting expression is determined by combining the component expressions, two at a time, until a final result is reached. Послідовність, в якій ці вирази об'єднуються, залежить від пріоритету операторів в вираженні. The sequence in which the expressions are combined is defined by the precedence of the operators in the expression.

Два вирази можна об'єднати будь-яким оператором, якщо обидва вони відносяться до типів даних, підтримуваним оператором, і виконується хоча б одна з таких умов. Two expressions can be combined by an operator if they both have data types supported by the operator and at least one of these conditions is true:

  • Вирази відносяться до одного типу даних. The expressions have the same data type.

  • Тип даних з більш низьким пріоритетом може бути неявно перетворений в тип даних з більш високим пріоритетом. The data type with the lower precedence can be implicitly converted to the data type with the higher data type precedence.

Якщо вираження не задовольняють цим умовам, функція CAST або CONVERT явно перетворює тип даних з більш низьким пріоритетом або в тип даних з більш високим пріоритетом, або в проміжний тип даних, який потім може бути неявно перетворений в тип даних з більш високим пріоритетом. If the expressions do not meet these conditions, the CAST or CONVERT functions can be used to explicitly convert the data type with the lower precedence to either the data type with the higher precedence or to an intermediate data type that can be implicitly converted to the data type with the higher precedence.

Якщо неявне або явне перетворення не підтримується, ці два вирази об'єднати неможливо. If there is no supported implicit or explicit conversion, the two expressions can not be combined.

Параметри сортування будь-якої вирази, результатом якого є символьний рядок, визначаються правилами черговості параметрів сортування. The collation of any expression that evaluates to a character string is set by following the rules of collation precedence. Додаткові відомості див. У статті Черговість параметрів сортування (Transact-SQL) . For more information, see Collation Precedence (Transact-SQL) .

У мові програмування, такому як C або Microsoft Microsoft Visual Basic Visual Basic, обчислення виразу завжди призводить до отримання єдиного результату. In a programming language such as C or Microsoft Microsoft Visual Basic Visual Basic, an expression always evaluates to a single result. Вирази в списку вибору інструкції мови Transact-SQL Transact-SQL підкоряються правилу, з якого випливає, що вираз застосовується окремо до кожного рядка в результуючому наборі. Expressions in a Transact-SQL Transact-SQL select list follow a variation on this rule: The expression is evaluated individually for each row in the result set. У окремих виразів можуть бути різні значення в кожному рядку результуючого набору, але у кожного рядка є тільки одне значення для вираження. A single expression may have a different value in each row of the result set, but each row has only one value for the expression. Наприклад, в наступній інструкції SELECT виразами є як посилання на ProductID, так і значення 1 + 2 в списку вибору: For example, in the following SELECT statement both the reference to ProductID and the term 1 + 2 in the select list are expressions:

USE AdventureWorks2012; GO SELECT ProductID, 1 + 2 FROM Production.Product; GO

Вираз 1 + 2 дає результат 3 в кожному рядку результуючого набору. The expression 1 + 2 evaluates to 3 in each row in the result set. Незважаючи на те, що вираз ProductID формує унікальне значення для кожного рядка в результуючому наборі, в кожному рядку міститься тільки одне значення для ProductID. Although the expression ProductID generates a unique value in each result set row, each row only has one value for ProductID.

Див. Також: See Also

AT TIME ZONE (Transact-SQL) AT TIME ZONE (Transact-SQL)
CASE (Transact-SQL) CASE (Transact-SQL)
Функції CAST і CONVERT (Transact-SQL) CAST and CONVERT (Transact-SQL)
COALESCE (Transact-SQL) COALESCE (Transact-SQL)
Перетворення типів даних (ядро СУБД) Data Type Conversion (Database Engine)
Пріоритет типів даних (Transact-SQL) Data Type Precedence (Transact-SQL)
Типи даних (Transact-SQL) Data Types (Transact-SQL)
Вбудовані функції (Transact-SQL) Built-in Functions (Transact-SQL)
LIKE (Transact-SQL) LIKE (Transact-SQL)
NULLIF (Transact-SQL) NULLIF (Transact-SQL)
SELECT (Transact-SQL) SELECT (Transact-SQL)
WHERE (Transact-SQL) WHERE (Transact-SQL)