在视图中向现有表添加新列

时间:2014-02-07 18:46:54

标签: sql sql-server

我有以下用于创建下表的SQL:

SELECT c.cOLUMN1 , c.cOLUMN2 , COALESCE (sc.cOLUMN3, 'XXX') AS cOLUMN3
FROM tabel AS c 


COLUMN1  COLUMN2   COLUMN3 

   1        1        XXX     
   1        1        26785  
   1        1        23432   
   1        1        XXX  

我想添加两个新列 - 如果column3中的值也相等'XXX'那么新的列 NEWCOLUMN_A 应为“0”且 NEWCOLUM_B 应为“1”。

否则 NEWCOLUMN_A 中的新内容应为“1”, NEWCOLUM_B 应为“1”。

如下图所示:

COLUMN1  COLUMN2   COLUMN3  NEWCOLUMN_A  NEWCOLUMN_B
   1        1        XXX       0            1  
   1        1        26785     1            1           
   1        1        23432     1            1 
   1        1        XXX       0            1 

4 个答案:

答案 0 :(得分:2)

SELECT 
    c.cOLUMN1 , 
    c.cOLUMN2 , 
    COALESCE (c.cOLUMN3, 'XXX') AS cOLUMN3,
    (CASE WHEN COALESCE(c.cOLUMN3, 'XXX') = 'XXX' THEN 0 ELSE 1 END) AS NEWCOLUMN_A,
    1 AS NEWCOLUMN_B
FROM tabel AS c

或者,由于第3列是派生的......

SELECT 
    c.cOLUMN1 , 
    c.cOLUMN2 , 
    COALESCE (c.cOLUMN3, 'XXX') AS cOLUMN3,
    (CASE WHEN c.cOLUMN3 IS NULL THEN 0 ELSE 1 END) AS NEWCOLUMN_A,
    1 AS NEWCOLUMN_B
FROM tabel AS c

答案 1 :(得分:0)

首先将列添加到表中:

ALTER TABLE tabel
    ADD NEWCOLUMN_A BIT NULL;
ALTER TABLE tabel
    ADD NEWCOLUMN_B BIT NULL;

然后UPDATE表:

UPDATE tabel
SET NEWCOLUMN_A = CASE WHEN COLUMN3 = 'XXX' THEN 0 ELSE 1 END,
    NEWCOLUMN_B = 1

答案 2 :(得分:0)

我认为这是你想要完成的事情。

Declare @string As nvarchar(50)
Set @string = 'xxx'
Select CASE WHEN @string  = 'xxx' Then 0 Else 1 End as NEWCOLUM_A, 1 as NEWCOLUM_B
set @string = 'yyy'
Select CASE WHEN @string  = 'xxx' Then 0 Else 1 End as NEWCOLUM_A, 1 as NEWCOLUM_B

答案 3 :(得分:0)

SELECT c.cOLUMN1 
     , c.cOLUMN2 
     , COALESCE(c.cOLUMN3, 'XXX') AS cOLUMN3
     , CASE WHEN c.cOLUMN3 IS NULL THEN 1 ELSE 0 END AS NEWCOLUMN_A 
     , 1 AS NEWCOLUM_B 
FROM tabel AS c