SQl事务 - 查询不按预期返回值

时间:2013-12-21 11:09:41

标签: c# sql stored-procedures

tblParent

pid(int) name deleted(bit)
1        abc   0
2        def   0

tblChild

cid(int) name  pid(ForeignKey)
1        aaa   1
2        bbb   1

当删除tblParent的记录时,应检查是否有任何子记录。如果是,回滚&返回0.如果否,则将已删除的列更新为' 1'并返回1。 基本上,做一个软删除

SP工作正常。我需要的是根据发生的动作将状态知道为0或1。应该怎么做。我会将此商店程序从c#,linq调用到实体以获取状态。  类似的东西:

public int somefuntion() //returning a string is also fine..
   {
     return MYDB.SoftDelete(parameters.....);
   }

修改

ALTER PROCEDURE SoftDelete
(
  @TableName nvarchar(50), @ColName nvarchar(50),
  @Id nvarchar(50)
)
AS
BEGIN
  DECLARE @qry nvarchar(500)

  SELECT @qry = 'begin transaction
                 delete '+@tablename+' where '+@colname+'='+@id+'
                 if(@@Error <> 0)
                  Begin
                    --select 0
                  End
                 else
                  Begin
                   rollback transaction
               update '+@tablename+' set deleted = 1 where '+@colname+' = '+@id+'
                   --select = 1
                  end'

   EXECUTE sp_executesql @qry
END

2 个答案:

答案 0 :(得分:1)

在您的脚本中,在您构建的sql语句中无法访问@status变量,因为“execute sp_executesql @qry”将在不同的空间中执行。而是使用select n“替换为”set @status = 0“和”set @status = 1“

试试这个

Declare @tablename nvarchar(50), @colname nvarchar(50),
        @id nvarchar(50), @qry nvarchar(500)
set @tablename  = 'tblParent'
set @colname = 'pid'
set @id = '1'

select @qry = 'begin transaction
               delete '+@tablename+' where '+@colname+'='+@id+'
               if(@@Error <> 0)
                Begin
                  select 0
                End
               else
                Begin
                 rollback transaction
               update '+@tablename+' set deleted = 1 where '+@colname+' = '+@id+'
                 select 1
                end

execute sp_executesql @qry

答案 1 :(得分:1)

试试这个:

Declare @status nvarchar(50),@tablename nvarchar(50), @colname nvarchar(50),
@id nvarchar(50), @qry nvarchar(500)
set @tablename  = 'person'
set @colname = 'id'
set @id = '15'
begin try
begin transaction
 set @qry='delete '+@tablename+' where '+@colname+'=@id'
 execute sp_executesql @qry,N'@id nvarchar(50)',@id=@id
 rollback 
 --NO FK violation.So begin another transaction and soft delete
 begin transaction
set @qry='update '+@tablename +' set deleted=1 where '+@colname+'=@id'

execute sp_executesql @qry,N'@id nvarchar(50)',@id=@id
commit

select 1

end try

begin catch
print(Error_Message())
--FK violation.Do nothing.Return 0
select 0

end catch