0

我有两个表tbl_itemtbl_category现在我要做的就是仅在没有所选类别的记录时删除所选内容category。如果删除存储过程应返回其他内容。请帮助。tbl_catetgorytbl_itemcategory10

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
4

3 回答 3

1

如果删除基于给定的单个类别,它作为参数@Code 提供,那么为什么需要游标和一些动态 sql。

从您的代码看来,两个表中都存在 Cat_Code 列;tbl_item 和 tbl_category。我也假设“Retun 1”仅在从 tabe tbl_category 中删除一行或多行时。

    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
于 2013-10-02T04:59:34.323 回答
1
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
于 2013-10-02T05:08:04.470 回答
0

如果您将参照完整性(即表之间的外键)添加到数据库,这将自动发生。

此外,不需要使用游标或动态 SQL 来实现这一点

于 2013-10-02T04:56:14.277 回答