COALESCE邏輯取值函式的用法 聯機幫助

2021-05-05 14:44:22 字數 2370 閱讀 4331

coalesce (transact-sql)

返回其引數中第乙個非空表示式。

transact-sql 語法約定

語法

coalesce ( expression [ ,...n ] )

引數 expression

任何型別的表示式。

返回型別

返回資料型別優先順序最高的 expression 的資料型別。如果所有表示式都不可為 null,則結果的型別也不可為 null。

注釋 如果所有引數均為 null,則 coalesce 返回 null。

示例 下面的示例演示 coalesce 如何從第乙個具有非 null 值的列中選擇資料。

use adventureworks ;

go

select name, class, color, productnumber,

coalesce(class, color, productnumber) as firstnotnull

from production.product ;

go

在以下示例中,wages表中包括以下三列有關雇員的年薪的資訊:hourly wage、salary 和 commission。但是,每個雇員只能接受一種付款方式。若要確定支付給所有雇員的金額總數,請使用coalesce僅接受在hourly_wagesalarycommission中找到的非 null 值。

複製**

set nocount on;

gouse tempdb;

if object_id('dbo.wages') is not null

drop table wages;

gocreate table dbo.wages

(    emp_id tinyint identity,

hourly_wage decimal null,

salary decimal null,

commission decimal null,

num_sales tinyint null

);go

insert dbo.wages (hourly_wage, salary, commission, num_sales)

values

(10.00, null, null, null),

(20.00, null, null, null),

(30.00, null, null, null),

(40.00, null, null, null),

(null, 10000.00, null, null),

(null, 20000.00, null, null),

(null, 30000.00, null, null),

(null, 40000.00, null, null),

(null, null, 15000, 3),

(null, null, 25000, 2),

(null, null, 20000, 6),

(null, null, 14000, 4);

goset nocount off;

goselect cast(coalesce(hourly_wage * 40 * 52,

salary,

commission * num_sales) as money) as 'total salary'

from dbo.wages

order by 'total salary';

go

下面是結果集:

total salary

20800.0000

41600.0000

62400.0000

83200.0000

10000.0000

20000.0000

30000.0000

40000.0000

45000.0000

50000.0000

120000.0000

56000.0000

(12 row(s) affected)

請參閱

參考isnull (transact-sql)

case (transact-sql)

幫助和資訊

獲取 sql server 2008 幫助

在多個表full join時方便select查詢篩選非空值的列。

COALESCE函式的用法

coalesce這個函式系統的用法如下 a.輸入引數為字元型別,且允許為空的,可以使用coalesce inputparameter,把null轉換成 b.輸入型別為整型,且允許為空的,可以使用coalesce inputparameter,0 把空轉換成0 c.輸入引數為字元型別,且是非空非空格的...

coalesce 函式詳解

coalesce 函式 返回列表中第乙個非null表示式的值。如果所有表示式求值為null,則返回null。coalesce expression 1,expression 2,expression n 依次參考各引數表示式,遇到非null值即停止並返回該值。如果所有的表示式都是空值,最終將返回乙個...

Coalesce 函式的全新認識

人們經常遇到coalesce 接合 函式,而他們大都把它看做是isnull 的乙個更有效的形式。事實上,我發現它是非常有用的函式而卻只有很少的文件。在這篇文章裡,筆者將為你展示coalesce 的基本使用以及一些你可能從沒見過的特性。讓我們首先從coalesce具有文件記錄的使用開始。根據msdn,...