[英]Check and delete stored procedure
我有两个表tbl_item
和tbl_category
,现在我要做的就是仅在tbl_item
没有选定类别的记录时才从tbl_catetgory
删除选定的category
。如果删除了category
则存储过程应返回1
否则为0
帮助。
ALTER PROCEDURE [dbo].[Sp_DelItemcategory]
@code int
AS
BEGIN
declare @sql varchar(max)
DECLARE @data VARCHAR(50)
set @sql='SELECT Cat_code FROM dbo.Tbl_ItemMaster WHERE Cat_code = '+@code;
declare dB_cursor cursor for
SELECT Cat_code FROM dbo.Tbl_ItemMaster WHERE Cat_code = @code
open dB_cursor
fetch next from dB_cursor into @data
WHILE @@FETCH_STATUS = 0
BEGIN
set @sql='delete from Tbl_ItemCategory where Cat_code='+@code;
exec @sql
FETCH NEXT FROM db_cursor INTO @data
END
CLOSE db_cursor
DEALLOCATE db_cursor
END
如果删除基于给定的单个类别(作为参数@Code提供),那么为什么需要游标和一些动态sql。
从您的代码看来,两个表中都存在Cat_Code列; tbl_item和tbl_category。 我也假设只有在从表tbl_category中删除了一行或多行时才使用“ Retun 1”。
if not exists(select top 1 1 from tbl_item where Cat_Code = @code)
begin
DELETE tbl_category where Cat_Code = @code
IF @@ROWCOUNT >0
RETURN 1
END
Else
BEGIN
RETURN 0
END
ALTER PROCEDURE [dbo].[Sp_DelItemcategory]
@code int
AS
if not exists(select * from tbl_item where Cat_Code = @code)
begin
if exists(select * from tbl_category where Cat_Code = @code)
begin
delete from tbl_category where Cat_Code = @code
return 1
end
end
return 0
如果您在数据库中添加参照完整性(即表之间的外键),则会自动发生。
此外,无需使用游标或动态SQL即可实现此目的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.