我有这个问题:
SELECT cod_commessa, (ISNULL(ccomm.costi, 0) + ISNULL(ccomm.imp_costi, 0) - ISNULL(ccomm.rid_costi, 0)) -
((SELECT ISNULL(costi, 0) AS Expr1
FROM t_costi_commesse AS tbs
WHERE (cod_commessa = ccomm.cod_commessa) AND (anno = YEAR(DATEADD(m, - 1, CAST(CAST(ccomm.anno AS varchar) + REPLICATE('0',
2 - LEN(CAST(ccomm.mese AS varchar))) + CAST(ccomm.mese AS varchar) + '01' AS smalldatetime)))) AND (mese = MONTH(DATEADD(m, - 1,
CAST(CAST(ccomm.anno AS varchar) + REPLICATE('0', 2 - LEN(CAST(ccomm.mese AS varchar))) + CAST(ccomm.mese AS varchar)
+ '01' AS smalldatetime))))) +
(SELECT ISNULL(imp_costi, 0) AS Expr1
FROM t_costi_commesse AS tbs
WHERE (cod_commessa = ccomm.cod_commessa) AND (anno = YEAR(DATEADD(m, - 1, CAST(CAST(ccomm.anno AS varchar) + REPLICATE('0',
2 - LEN(CAST(ccomm.mese AS varchar))) + CAST(ccomm.mese AS varchar) + '01' AS smalldatetime)))) AND (mese = MONTH(DATEADD(m, - 1,
CAST(CAST(ccomm.anno AS varchar) + REPLICATE('0', 2 - LEN(CAST(ccomm.mese AS varchar))) + CAST(ccomm.mese AS varchar)
+ '01' AS smalldatetime))))) -
(SELECT ISNULL(rid_costi, 0) AS Expr1
FROM t_costi_commesse AS tbs
WHERE (cod_commessa = ccomm.cod_commessa) AND (anno = YEAR(DATEADD(m, - 1, CAST(CAST(ccomm.anno AS varchar) + REPLICATE('0',
2 - LEN(CAST(ccomm.mese AS varchar))) + CAST(ccomm.mese AS varchar) + '01' AS smalldatetime)))) AND (mese = MONTH(DATEADD(m, - 1,
CAST(CAST(ccomm.anno AS varchar) + REPLICATE('0', 2 - LEN(CAST(ccomm.mese AS varchar))) + CAST(ccomm.mese AS varchar)
+ '01' AS smalldatetime)))))) AS 'costi'
FROM t_costi_commesse AS ccomm INNER JOIN
t_commesse AS comm ON ccomm.cod_commessa = comm.codcema
此查询正确返回值,但有时我在列' costi'中有一些值。即使我将ISNULL应用于每个值,它仍然是NULL。奇怪的是,有时NULL值被正确地替换为0,但有时不会。
我还确定原始值为NULL(而不是字符串' NULL'),因为SQL Server Management Studio正确更改了背景颜色。
所以,我可以理解我的查询是否不正确,或者ISNULL因未知原因而无法正常工作。有什么建议吗?
答案 0 :(得分:2)
将您在子查询中应用的ISNULL
移至外部。
此:
select 1,(select object_id from sys.objects where 1=0)
产地:
1, NULL
尽管object_id
不可以为空,但子查询不返回任何行。您无法在子查询的select
中修复它,因为没有行。所以这个:
select 1,(select ISNULL(object_id,0) from sys.objects where 1=0)
没有解决问题但是:
select 1,ISNULL((select object_id from sys.objects where 1=0),0)
确实