简体   繁体   中英

How to deleted record as false in SQL Server from winforms UI using c#?

I have a problem to set deleted record as false in my SQL Server.I tried a lot.

My problem is i have a table in some Of the columns id,name etc...id as primary key constraint. When the user delete the record? so that record should be present on the table. i will make that record as false in my table?

In future he want to add the record with the deleted id? we give the chance to add a record with that id?

plz tell me the example of doing this? i tried a lot but i don't know. because primary key doesn't accept duplicates so i strucked here.

My delete stored procedure:

If user press the delete button in my UI:

This stored procedure is execute in my back-end:

update table set id=id*-1, flag=1 where id=@id and flag=0;

In front i have shown record is deleted.

But if he want to add the record with that deleted id. Primary key voilation error from my database.when he insert the record.

Thanks

  1. Add a column DeleteFlag bit into the table, set to false by default.
  2. Always add the where condition WHERE DeleteFlag = 0 to display data in UI
  3. Update the column to true if user "delete" the record from UI

Do not alter primary key, they are not intended to change.

EDIT

To reuse the deleted Id , you can negate the Id and mark the record as deleted. However, this is not recommended to update the primary key in normal case.

example

UPDATE id = -1 * id, flag = 1 WHERE id = @id and flag = 0;

EDIT 2

Missed if the use delete the new record with same deleted id, just negate the id is not enough.

UPDATE t SET id = newId.Value, flag = 1, new_field=@id     
FROM table t CROSS APPLY
(
    SELECT CASE WHEN MIN(Id) >= 0 THEN -1 ELSE MIN(Id) - 1 END AS value 
    FROM table with(updlock)
) AS newId
WHERE t.id = @id AND flag = 0

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