I need to compare two row with each other and then write the fields that changed into a table.
My table:
CREATE TABLE dbo.tUserChanges
(
cID int IDENTITY (1,1),
cChangeDate DateTime,
cValueChanged varchar(30),
cPreviousValue bit,
cCurrentValue bit
)
In my C# program the user table needs to be updated when changes are made to the users.
This is done with a stored procedure:
CREATE PROCEDURE [dbo].[UUser]
(
@User as varchar(15),
@UCode AS int,
@UName AS varchar(30),
@UID AS varchar(10),
@UPassword AS varchar(15),
@UPMaintenance as bit,
@UClient as bit,
@UFinancial as bit,
@UViewReceiptImage bit,
@UViewPayrollData bit
)
AS
BEGIN
UPDATE tUsers
SET
UName = @UName,
UID = @UID,
UPassword = @UPassword, UPMaintenance = @UPMaintenance,
UClient = @UClient,
UFinancial = @UFinancial,
UViewReceiptImage = @UViewReceiptImage,
UViewPayrollData = @UViewPayrollData
WHERE UCode = @UCode
END
There is more values in the tUser table but for the sake of keeping it sort I removed some of the values.
So what I need to do is create a temp table at the befor I update the tUsers table so that I can Compare the two rows after the update has been done and then right the changes that took place into the new table.
I have tried this but I know there is a better way and it also does not give the required results:
declare @i int
set @i = 0
declare @ColumnCount int
set @ColumnCount = (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = @UID)
declare @ColumnName varchar(30)
set @ColumnName = (select column_name from information_schema.columns where table_name = 'tUsers' and ordinal_position = 14)
select UActivateLoan from tusers
while (@ColumnCount < @i)
Begin
if((select @ColumnName from tUsers where UID = @UID)
<> (select @ColumnName from #myTemp where UID = @UID))
Begin
Insert into tUserChanges
Values(GETDATE(),(select column_name from information_schema.columns where table_name = 'tUsers' and ordinal_position = 14),
(select(select column_name from information_schema.columns where table_name = 'tUsers' and ordinal_position = 14) from #myTemp where UID = @UID),
(select(select column_name from information_schema.columns where table_name = 'tUsers' and ordinal_position = 14) from tUsers where UID = @UID))
END
set @i = @i + 1
End
I am not sure if I will need to use a cursor here or what I can do to get the result? Any help would be appreciated.