比較運算子 (Transact-SQL)Comparison Operators (Transact-SQL)

適用於: 是SQL Server (從 2012 開始) 否Azure SQL Database 否Azure SQL 資料倉儲 否平行處理資料倉儲 APPLIES TO: yesSQL Server (starting with 2012) noAzure SQL Database noAzure SQL Data Warehouse noParallel Data Warehouse

比較運算子用來測試兩個運算式是否相同。Comparison operators test whether two expressions are the same. 除了 textntextimage 資料類型的運算式,所有運算式都可使用比較運算子。Comparison operators can be used on all expressions except expressions of the text, ntext, or image data types. 下表會列出 Transact-SQLTransact-SQL 比較運算子。The following table lists the Transact-SQLTransact-SQL comparison operators.

運算子Operator 意義Meaning
= (等於)= (Equals) 等於Equal to
> (大於)> (Greater Than) 大於Greater than
< (小於)< (Less Than) 小於Less than
>= (大於或等於)>= (Greater Than or Equal To) 大於或等於Greater than or equal to
<= (小於或等於)<= (Less Than or Equal To) 小於或等於Less than or equal to
<> (不等於)<> (Not Equal To) 不等於Not equal to
!= (不等於)!= (Not Equal To) 不等於 (不是 ISO 標準)Not equal to (not ISO standard)
!< (不小於)!< (Not Less Than) 不小於 (不是 ISO 標準)Not less than (not ISO standard)
!> (不大於)!> (Not Greater Than) 不大於 (不是 ISO 標準)Not greater than (not ISO standard)

布林資料類型Boolean Data Type

比較運算子的結果具有 Boolean 資料類型。The result of a comparison operator has the Boolean data type. 它有三個值:TRUE、FALSE 和 UNKNOWN。This has three values: TRUE, FALSE, and UNKNOWN. 傳回 Boolean 資料類型的運算式稱為布林運算式。Expressions that return a Boolean data type are known as Boolean expressions.

Boolean 資料類型和其他 SQL ServerSQL Server 資料類型不同,不能將它指定為資料表資料行或變數的資料類型,且無法在結果集中傳回。Unlike other SQL ServerSQL Server data types, a Boolean data type cannot be specified as the data type of a table column or variable, and cannot be returned in a result set.

當 SET ANSI_NULLS 是 ON 時,有一或兩個 NULL 運算式的運算子會傳回 UNKNOWN。When SET ANSI_NULLS is ON, an operator that has one or two NULL expressions returns UNKNOWN. 當 SET ANSI_NULLS 是 OFF 時,會套用相同的規則,但等於 (=) 和不等於 (<>) 運算子除外。When SET ANSI_NULLS is OFF, the same rules apply, except for the equals (=) and not equals (<>) operators. 當 SET ANSI_NULLS 是 OFF 時,這些運算子會將 NULL 視為已知值,等同於任何其他 NULL,並且只會傳回 TRUE 或 FALSE (絶不會是 UNKNOWN)。When SET ANSI_NULLS is OFF, these operators treat NULL as a known value, equivalent to any other NULL, and only return TRUE or FALSE (never UNKNOWN).

在 WHERE 子句中使用含 Boolean 資料類型的運算式,來篩選符合搜尋條件,且在 IF 和 WHILE 之類流程控制語言陳述式中的資料列,例如:Expressions with Boolean data types are used in the WHERE clause to filter the rows that qualify for the search conditions and in control-of-flow language statements such as IF and WHILE, for example:

-- Uses AdventureWorks  
  
DECLARE @MyProduct int;  
SET @MyProduct = 750;  
IF (@MyProduct <> 0)  
   SELECT ProductID, Name, ProductNumber  
   FROM Production.Product  
   WHERE ProductID = @MyProduct;  

另請參閱See Also

運算式 (Transact-SQL)Expressions (Transact-SQL)
運算子 (Transact-SQL)Operators (Transact-SQL)