coalesce的用法

mac2022-06-30  12

语法

COALESCE ( e­xpression [ ,...n ] )

备注 如果所有参数均为 NULL,则 COALESCE 返回 NULL。

注意: 至少应有一个空值为 NULL 类型。

COALESCE(e­xpression1,…n) 与此 CASE 函数等效:

复制代码 CASE WHEN (e­xpression1 IS NOT NULL) THEN e­xpression1 WHEN (e­xpressionN IS NOT NULL) THEN e­xpressionN ELSE NULL END

参数 e­xpression 任何类型的表达式。

返回类型 返回数据类型优先级最高的 e­xpression 的数据类型。

示例 在 以下示例中,wages 表中包括以下三列有关雇员的年薪的信息:hourly wage、salary 和 commission。但是,每个雇员只能接受一种付款方式。若要确定支付给所有雇员的金额总数,请使用 COALESCE 函数,它只接受在 hourly_wage、salary 和 commission 中找到的非空值。

复制代码 SET NOCOUNT ON; GO USE master; IF EXISTS (Select name FROM sys.tables Where name = ‘wages’) Drop TABLE wages; GO Create TABLE wages ( emp_id      tinyint    identity, hourly_wage   decimal   NULL, salary      decimal    NULL, commission   decimal   NULL, num_sales   tinyint   NULL ); GO Insert wages VALUES(10.00, NULL, NULL, NULL); Insert wages VALUES(20.00, NULL, NULL, NULL); Insert wages VALUES(30.00, NULL, NULL, NULL); Insert wages VALUES(40.00, NULL, NULL, NULL); Insert wages VALUES(NULL, 10000.00, NULL, NULL); Insert wages VALUES(NULL, 20000.00, NULL, NULL); Insert wages VALUES(NULL, 30000.00, NULL, NULL); Insert wages VALUES(NULL, 40000.00, NULL, NULL); Insert wages VALUES(NULL, NULL, 15000, 3); Insert wages VALUES(NULL, NULL, 25000, 2); Insert wages VALUES(NULL, NULL, 20000, 6); Insert wages VALUES(NULL, NULL, 14000, 4); GO SET NOCOUNT OFF; GO Select CAST(COALESCE(hourly_wage * 40 * 52, salary, commission * num_sales) AS money) AS ‘Total Salary’ FROM wages; 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)

转载于:https://www.cnblogs.com/Gaojier/archive/2010/04/08/2783598.html

最新回复(0)