Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Stored Procedure For A Soft Delete

Author  Topic 

sharpcnet
Starting Member

8 Posts

Posted - 2013-12-22 : 08:22:29
This code is to perform a Soft Delete. It deletes a record first. If the delete was successful, rollsback and then updates the flag column of the same record. If that record has dependencies and could not be deleted, does nothing. In order to know, the action happened, I kept the Status variable. But, it always results as null, no matter what. Where am I going wrong.

ALTER PROCEDURE SoftDelete
(
@TableName nvarchar(50), @ColName nvarchar(50),
@Id nvarchar(50)
)
AS
BEGIN
DECLARE @qryDel nvarchar(MAX),@qryUpd nvarchar(MAX),@Status int = null

SET @qryDel = 'delete from'+@tablename+' where '+@colname+'='+@id
SET @qryUpd = 'update '+@tablename+' set deleted = 1 where '+@colname+' = '+@id

BEGIN TRY
BEGIN TRANSACTION
EXECUTE sp_executesql @qryDel
ROLLBACK TRANSACTION
BEGIN TRANSACTION
EXECUTE sp_executesql @qryUpd
COMMIT TRANSACTION
SET @Status = 1
END TRY

BEGIN CATCH
ROLLBACK TRANSACTION
SET @Status = 0
END CATCH

SELECT @Status

END

C#:(Linq To Entities)

public int SoftDelete()
{
return MYDB.SoftDelete("tblCountry","CountryId,"101").FirstOrDefault ?? -1;
}


bitsmed
Aged Yak Warrior

545 Posts

Posted - 2013-12-22 : 08:37:48
Instead of "select @status" at the end of the procedure, try "return @status"
Go to Top of Page

sharpcnet
Starting Member

8 Posts

Posted - 2013-12-22 : 08:56:46
Should I have an output parameter then? I dteclared one @Status int out.
When I execute the SP from SS2008, it gives two results - @Status - 0 ; Return Value - 0. - For every record.

Go to Top of Page

bitsmed
Aged Yak Warrior

545 Posts

Posted - 2013-12-22 : 12:17:51
quote:
Originally posted by sharpcnet

Should I have an output parameter then? I dteclared one @Status int out.
When I execute the SP from SS2008, it gives two results - @Status - 0 ; Return Value - 0. - For every record.

According to [url]http://technet.microsoft.com/en-us/library/ms174998.aspx[/url], you don't need to specify an output variable.
Go to Top of Page

Lamprey
Master Smack Fu Yak Hacker

4614 Posts

Posted - 2013-12-23 : 14:17:07
I'm not sure of your goal. But, I'd suggest loosing the status and just use structured error handling (as in re-THROW the error, if any). But, up to you.
Go to Top of Page
   

- Advertisement -