sql查询删除并返回消息

时间:2016-11-10 10:04:01

标签: sql-server

我想写一些像查询这样的东西:

BEGIN

DECLARE @Unaloacte varchar(200);
DECLARE @Total int;
DECLARE @Flag int;

SET @Unaloacte =( Select count(PD.PropertyDetailId) from PropertyDetail AS PD join 
SiteDetail AS SD ON PD.SiteDetailId=SD.SiteDetailId  Where PD.CustomerId<1 and PD.SiteDetailId=27);

SET @Total= (Select count(PropertyDetailId) as Total_Count from PropertyDetail where SiteDetailId=27) ;

if( @Unaloacte = @Total)
Delete something and display message
print"Delete";
else

print"Not able to delete"

END

我希望你能理解我的问题。

2 个答案:

答案 0 :(得分:0)

您可以尝试这样:

DECLARE @Msg VARCHAR(200)

if( @Unaloacte = @Total)
BEGIN
BEGIN TRAN

DELETE something 

SELECT @Msg = CAST(@@ROWCOUNT AS VARCHAR(10)) + ' are deleted'
RAISERROR (@Msg, 0, 1) WITH NOWAIT

COMMIT
END

ELSE
BEGIN
SELECT 'Not able to delete'
END

如果您打算在制作中使用,我还建议您使用BEGIN TRANCOMMIT

答案 1 :(得分:0)

您可以使用@@ROWCOUNTSET NOCOUNT ON

进行检查
SET NOCOUNT ON
DELETE FROM TableName
IF @@ROWCOUNT > 0
  PRINT 'Record Deleted'
ELSE 
  PRINT 'Record Not Deleted' 

此处使用SET NOCOUNT ON,因为我们不希望看到受影响的行数消息。