我有一个包含两个int列的表,并尝试以下操作:在该表的SELECT
语句中,如果此值之一为0,则该列将为空。
我尝试使用此SQL,但后来却得到0
而不是''
:
SELECT
Typ
, Nummer
, IIF(ATBPos > 0 , ATBPos, '') AS ATBPos
, IIF(ATBStk > 0 , ATBStk, '') AS ATBStk
, ID
FROM
Vorpapier
WHERE
FremdID = 1
AND PosNummer = 1
表Vorpapier
看起来像这样:
Nummer (varchar) | ATBPos (int) | ATbStk (int) | Typ (varchar)
-----------------+--------------+--------------+--------------
54542542542 | 0 | 0 | OHNE
45454 | 15 | 45 | ATB
结果应如下所示:
Nummer (varchar) | ATBPos (int) | ATbStk (int) | Typ (varchar)
-----------------+--------------+--------------+--------------
54542542542 | | | OHNE
45454 | 15 | 45 | ATB
答案 0 :(得分:3)
只需使用
iif( ATBPos = 0, null, ATBPos ) as ATBPos
和
iif( ATBStk = 0, null, ATBStk ) as ATBStk
答案 1 :(得分:2)
您可以转换为varchar。
SELECT
Typ
, Nummer
, IIF(ATBPos > 0 , cast(ATBPos as varchar), '') AS ATBPos
, IIF(ATBStk > 0 , cast(ATBStk as varchar), '') AS ATBStk
, ID
FROM
Vorpapier
WHERE
FremdID = 1
AND PosNummer = 1
答案 2 :(得分:1)
尝试一下:-
SELECT
Typ
, Nummer
, (CASE WHEN ATBPos > 0 then ATBPos ELSE '' END) as ATBPos
, (CASE WHEN ATBStk > 0 then ATBStk ELSE '' END) as ATBStk
, ID
FROM
Vorpapier
WHERE
FremdID = 1
AND PosNummer = 1
或者您应该在SQL查询中将IIF更改为if。也尝试:-
SELECT
Typ
, Nummer
, IF(ATBPos > 0 , ATBPos, '') AS ATBPos
, IF(ATBStk > 0 , ATBStk, '') AS ATBStk
, ID
FROM
Vorpapier
WHERE
FremdID = 1
AND PosNummer = 1
答案 3 :(得分:1)
在SQL中,表达式返回特定类型。在这种情况下,类型是数字,而''
不是数字。因此,它将转换为0
的来源。
解决方案是使用兼容类型。我建议使用case
表达式(case
是标准SQL的一部分)。看起来像:
SELECT Typ, Nummer,
(CASE WHEN ATBPos > 0 THEN ATBPos END) AS ATBPos,
(CASE WHEN ATBStk > 0 THEN ATBStk END) AS ATBStk, ID
FROM Vorpapier
WHERE FremdID = 1 AND
PosNummer = 1;
或者,如果您确实希望使用空白字符串而不是NULL
,请使用类型转换:
SELECT Typ, Nummer,
(CASE WHEN ATBPos > 0 THEN CAST(ATBPos as VARCHAR(255)) ELSE '' END) AS ATBPos,
(CASE WHEN ATBStk > 0 THEN CAST(ATBStk as VARCHAR(255)) ELSE '' END) AS ATBStk, ID
FROM Vorpapier
WHERE FremdID = 1 AND
PosNummer = 1;