我想验证一行是否已删除。我将表名和有问题的值传递给我的存储过程。它删除了所述项目,但我认为我会验证它实际上已被删除。所以我创建了@ItemFound,并希望让它等于计数。但它没有设置,因为它在我正在构建的SQL字符串的内部。 如何创建SQL字符串,执行它,将结果设置为变量,然后稍后检查变量?
Create Procedure MyProcedure
(@UPCode varchar(20),
@Tablename varchar(200))
AS
Declare @SQLString varchar(1000)
Select @SQLString = ('Delete from ' + @Tablename + ' Where [UPCode] = ''' + @UPCode + '''')
print @SQLString
--[My Table name]
EXEC(@SQLString)
-- area of issue where
Declare @ItemFound as int
Declare @SQLString2 varchar(500)
-- this gave error @ItemFound not declared so I added it to the string I'm building. but its not available outside.
Select @SQLString2 = ('Declare @ItemFound as int; set @ItemFound = (Select count(*) from ' + @Tablename + ' Where UPCode = ''' + @UPCode + ''')')
print @SQLString2
EXEC(@SQLString2)
-- @ItemFound is not equal to zero so it returns 'Item NOT Deleted'
If @ItemFound = 0
Begin
Select 'Item Deleted'
End
else
Begin
Select 'Item NOT Deleted'
End
感谢您的帮助。
答案 0 :(得分:1)
只需恢复执行顺序:在@SQLString
之前执行@ SQLString2Create Procedure MyProcedure
(@UPCode varchar(20),
@Tablename varchar(200))
AS
Declare @SQLString2 varchar(500)
-- this gave error @ItemFound not declared so I added it to the string I'm building. but its not available outside.
Select @SQLString2 = ('Declare @ItemFound as int; set @ItemFound = (Select count(*) from ' + @Tablename + ' Where UPCode = ''' + @UPCode + ''')')
print @SQLString2
EXEC(@SQLString2)
Declare @SQLString varchar(1000)
Select @SQLString = ('Delete from ' + @Tablename + ' Where [UPCode] = ''' + @UPCode + '''')
print @SQLString
--[My Table name]
EXEC(@SQLString)
-- area of issue where
Declare @ItemFound as int
-- @ItemFound is not equal to zero so it returns 'Item NOT Deleted'
If @ItemFound = 0
Begin
Select 'Item Deleted'
End
else
Begin
Select 'Item NOT Deleted'
End
另一种解决方案可能是在您的删除语句中使用OUTPUT
:
More infos