简体   繁体   中英

Check column value and update another column value from same table

I have 2 tables Table A and Table B. Based on some conditions by joining Table A and Table B, I am inserting values into table C.

In table C, I am inserting values by using insert into select query. Lets say table C has 4 columns, my 2nd column value depends on the 1st column value ie, if column 1 value is <0 then insert column 2 value as 'F' or else 'T'. So how can I insert value into column 2 by computing the value from column 1 in the same table.

Schema:

INSERT INTO #TableC
SELECT
    B.STORE AS WS_AUTH_STR,
    (CASE
        WHEN (B.DATE /17) = substring(cast([A_EXT_AUTH_CD] as varchar(10)),1, 4) THEN (B.DATE /17)
        WHEN (B.DATE /17) = substring(cast([A_EXT_AUTH_CD] as varchar(10)),2, 5) THEN (B.DATE /17)
        WHEN (B.DATE /17) = substring(cast([A_EXT_AUTH_CD] as varchar(10)),3, 6) THEN (B.DATE /17)
        WHEN (B.DATE /23) = substring(cast([A_EXT_AUTH_CD] as varchar(10)),1, 4) THEN (B.DATE /23)
        WHEN (B.DATE /23) = substring(cast([A_EXT_AUTH_CD] as varchar(10)),2, 5) THEN (B.DATE /23)
        WHEN (B.DATE /23) = substring(cast([A_EXT_AUTH_CD] as varchar(10)),3, 6) THEN (B.DATE /23)
        ELSE A_AUTH_CD
     END) AS WS_AUTH_AUTH_CODE,
     COLUMN N
FROM TableA A
INNER JOIN TableB B ON A.STORE = B.STORE;

In order to insert into column N, first I need to check WS_AUTH_AUTH_CODE value. If it is (B.DATE /17), then insert 1 to this column or else 2.

You can use CASE to achieve your requirement. The select statement would be as below-

INSERT INTO....
....
SELECT A.Some_column AS Column_1,
CASE 
    WHEN A.Some_column = 0 THEN 'F' 
    ELSE 'T' 
END AS Column_2
FROM Some_table A

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM