如何在SQL语句中,将计算列设为%格式的计算列,是两列想除的结果

解决方案 »

  1.   

    select rtrim((1.0*f1 / isnull(nullif(f2,0),1)/*除0处理*/  )*100) + '%' from tb
      

  2.   

    select a,b,c=case when b<> 0 then cast(cast(a*100.0/b decimal(18,2)) as varchar) + '%' else 'b列为0,不能除' end from tb
      

  3.   


    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[tb1]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[tb1]
    GOCREATE TABLE [dbo].[tb1] (
    [col1] [numeric](18, 2) NULL ,
    [col2] [numeric](18, 2) NULL ,
    [col3] AS (case when (isnull([col2],0) = 0) then null else (str(([col1] / [col2] * 100),18,2) + '%') end) 
    ) ON [PRIMARY]
    GO
      

  4.   


    CREATE TABLE [dbo].[tb1] (
        [col1] [numeric](18, 2) NULL ,
        [col2] [numeric](18, 2) NULL ,
        [col3] AS (case when (isnull([col2],0) = 0) then null else ltrim(str(([col1] / [col2] * 100),18,2) + '%') end) 

    insert into tb1
    select 12.00,100.00
    union all select 35.00,70.00
    union all select 45.00,0 
    union all select 345.00,1000.00
    union all select 12.00,nullselect *
    from tb1
    /*
    col1                 col2                 col3                
    -------------------- -------------------- ------------------- 
    12.00                100.00               12.00%
    35.00                70.00                50.00%
    45.00                .00                  NULL
    345.00               1000.00              34.50%
    12.00                NULL                 NULL(所影响的行数为 5 行)
    */