简体   繁体   中英

SQL Query to compare 2 rows and store the differences in variables C#?

I am currently working on a project that is looking at having a database that will store only 2 rows of data in it. This database will have new rows added to it all the time and the top row will be deleted when a new row is entered making sure there are always 2 rows.

What I am looking to do is to compare the top row of data and the bottom row of data and then store the data that is different in variables. I only want to store the data that is different from the bottom row as the top row will always be the oldest sets of data and I would no longer need to handle that.

I can do this all on the C# side but I was wondering if there is a way to do most of this on the SQL side of things? Thanks for the help :-)

thanks for the clearification, let assume this table:

create table temp_monitor(id int, stamp datetime, @newTemp1 float, @newTemp2 float)

then this stored procedure should do the trick

create proc updateTempMonitor(temp_oven_1 float, temp_oven_2 float)
as

-- save the values where about to replace
declare @id int, @t1 float, @t2 float
select top 1 @id = id, @t1 = temp_oven_1, @t2 = temp_oven_2 from temp_monitor order by stamp

-- update the oldest
update updateTempMonitor set temp_oven_1 = @newTemp1, temp_oven_2 = @newTemp2 where id = @id

-- return data to caller (c#)
select @t1, @t2

It is possible in both side C# and SQL,

SQL side you need to write SP or something which will return you pivot with the diff in the form of column name and changed columns.

look here for more . SQL Rows to Columns

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