简体   繁体   中英

Insert records into a table with IF statement from a temp in SQL Server 2016

I have a table table1 that has some columns, which has to be calculated and moved into another table table2 based on some conditions. To meet the conditions, I created a temp table #ttemp and altered the temp table to with creating two new variables var1 and var2 to set some values based on different columns and later check those conditions. If conditions pass, I do some aggregation and then later I would insert into table2 that will have aggregated columns.

First, create the #temp table and variables from table1 .

SELECT * 
INTO #ttemp
FROM table1

alter table #ttemp add var1 int
alter table #ttemp add var2 int

update #ttemp set var1 = -1

update #ttemp set var1 = 1
where error <> 0 and var1 = -1

update #ttemp var2 = -1

Next, values of var1 column and var2 columns' values from #temp table ( var1 = 0 and var2 = -1 ) and calculate average of cus_request , cus_stay and put them in a new temp table #ttemp2 .

IF var2 = -1 and var1 = 0
   BEGIN
   select y.id, y.avg(cus_request) as r_avg, y.avg(cust_stay) as s_avg
   INTO #ttemp2
   FROM #ttemp as y

   UPDATE l
   SET l.cus_request_avg = t.r_avg, l.cust_stay_avg = t.s_avg
   FROM table2 as l
   inner join #ttemp2 as t
   t.id = l.id

END

My problem is, my IF statement is not working and if I just run the select statements and update statement it works fine, but after update statement, it I get 0 rows affected as conditions do not meet. I am using update instead of insert statement. How can insert records into table2 ?

Any help would appreciated.

I think you are misusing IF.

IF would compare two values, not look through two columns and pick out the data where the conditions are met.

I think you could achieve what you are after with a WHERE clause:

   SELECT avg(y.cus_request) AS r_avg, avg(y.cust_stay) AS s_avg
   INTO #ttemp2 as t2
   FROM #ttemp as y
   WHERE    y.var2 = -1 AND y.var1 = 0

   UPDATE l
   SET l.cus_request_avg = t.r_avg, 
       l.cust_stay_avg = t.s_avg
   FROM table2 as l
   inner join #ttemp2 as t ON t.id = l.id

To answer the question in the comments....

To just insert into the table, it is:

INSERT INTO table2 
        (
            cus_request_avg ,
            cust_stay_avg
        )
SELECT      t.r_avg         ,
            t.s_avg
FROM        #ttemp2     AS t;

To insert only where the records do not exist in table2:

INSERT INTO table2 
        (
            cus_request_avg ,
            cust_stay_avg
        )
SELECT      t.r_avg         ,
            t.s_avg
FROM        #ttemp2     AS t
LEFT JOIN   table2      AS l ON t.id = l.id
WHERE       l.id IS NULL;

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