NULL将在SQL Server中转换为空白

时间:2014-07-30 13:21:19

标签: sql sql-server view

转换Null for float Columns时遇到问题。我需要一个输出,其中NULL将转换为空白,如果它不是NULL,那么它将正确输出任何精度值丢失。

示例,我在下面的表“tbl_cost”:

PROD_ID  INT
IND_COST FLOAT(10,8)
PAK_COST FLOAT(10,8)

我已为上表编写了一个视图

Create View v_Cost
Begin 
    SELECT PROD_ID, IND_COST, PAK_COST
    FROM tbl_cost
End 

以下是我对查看的查询:

SELECT PROD_ID,
       CASE WHEN IND_COST IS NULL THEN '' ELSE  IND_COST END AS  IND_COST,
       CASE WHEN IND_COST IS NULL THEN '' ELSE  IND_COST END AS  IND_COST
FROM v_cost

我只需要查看查询。在此先感谢您的帮助。

谢谢, Ajit

2 个答案:

答案 0 :(得分:1)

请试试这个

CREATE VIEW v_Cost
BEGIN
    SELECT PROD_ID,
          ISNULL(LTRIM(Str(IND_COST, 25, 5)), '') AS IND_COST,
          ISNULL(LTRIM(Str(PAK_COST, 25, 5)), '') AS PAK_COST
    FROM @tbl_cost
END 

<强>测试

DECLARE @tbl_cost TABLE (PROD_ID  INT,
                    IND_COST FLOAT(18),
                    PAK_COST FLOAT(18))
INSERT INTO  @tbl_cost
VALUES
(1, '32.5087', '2.00'),
(2, NULL, '32.50869'),
(3, '1.0000', NULL),
(4, NULL, NULL)

SELECT PROD_ID,
      ISNULL(LTRIM(Str(IND_COST, 25, 5)), '') AS IND_COST,
      ISNULL(LTRIM(Str(PAK_COST, 25, 5)), '') AS PAK_COST
FROM @tbl_cost

答案 1 :(得分:0)

根据@AjitKadam的作者请求更改范围。 十进制尾随零删除

Example:
1.00000  -> 1
32.50869 -> 32.50869
32.50870 -> 32.5087
1.00100  -> 1.001

<强>脚本:

DECLARE @tbl_cost TABLE (PROD_ID  INT,
                    IND_COST FLOAT(18),
                    PAK_COST FLOAT(18))
INSERT INTO  @tbl_cost
VALUES
(1, '32.5087', '2.00'),
(2, NULL, '32.50869'),
(3, '1.0010', NULL),
(4, NULL, NULL)

;WITH cte_Result AS
(
SELECT PROD_ID,
      ISNULL(LTRIM(Str(IND_COST, 25, 5)), '') AS IND_COST,
      ISNULL(LTRIM(Str(PAK_COST, 25, 5)), '') AS PAK_COST
FROM @tbl_cost
),cte_ResultFinal AS
(
select *
       ,CASE WHEN LEN(IND_COST)>0 THEN SUBSTRING(IND_COST,1,CHARINDEX('.',IND_COST)-1) ELSE '' END AS A_IND_COST
       ,CASE WHEN LEN(PAK_COST)>0 THEN SUBSTRING(PAK_COST,1,CHARINDEX('.',PAK_COST)-1) ELSE '' END AS A_PAK_COST
       ,REVERSE(CAST(REVERSE(SUBSTRING(IND_COST,CHARINDEX('.',IND_COST)+1,LEN(IND_COST))) AS INT)) as B_IND_COST
       ,REVERSE(CAST(REVERSE(SUBSTRING(PAK_COST,CHARINDEX('.',PAK_COST)+1,LEN(PAK_COST))) AS INT)) AS B_PAK_COST
from cte_Result
)
SELECT PROD_ID,
      A_IND_COST+CASE WHEN B_IND_COST ='0' THEN '' ELSE '.'+B_IND_COST END AS IND_COST,
      A_PAK_COST+CASE WHEN B_PAK_COST ='0' THEN '' ELSE '.'+B_PAK_COST END AS PAK_COST
FROM cte_ResultFinal