仅执行动态查询以获得受影响的行数

时间:2018-07-10 11:06:20

标签: sql sql-server execute dynamicquery

我想执行动态查询以获取受影响的行数。但是“ SQL结果”窗格执行完后会返回结果。如何避免返回列。我尝试了以下方法。

DECLARE @Command NVARCHAR(MAX)= 'SELECT * FROM Product  WHERE ID = 12'
DECLARE @Count AS INT
EXEC sp_executesql @Command, N'@C INT OUTPUT', @C=@Count OUTPUT
  IF (@Count > 0)
   BEGIN
    EXECUTE (@Command)
   END
  ELSE
   BEGIN
    DECLARE @CatalogProduct VARCHAR(MAX) = 'SELECT p.ManufactureCode,p.PartNo,p.Size,p.ID AS ProductID,p.Name ,p.ParentProductID,p.BasePrice FROM Product.Product p WHERE p.ThruDate > GETDATE() '+@Where
            EXECUTE (@CatalogProduct)
   END
END

Issue

我想避免从上面的图片返回空列集。

4 个答案:

答案 0 :(得分:1)

您可以关闭显示屏。但是,我认为一种更好的方法是直接获取您想要的数量:

DECLARE @Command NVARCHAR(MAX)= 'SELECT * FROM Product  WHERE ID = 12';

DECLARE @count AS INT;
DECLARE @CntCommand NVARCHAR(MAX);

SET @CntCommand = 'SELECT @count = COUNT(*) FROM (' + @Command + ') x)

EXEC sp_executesql @CntCommand, N'@count INT OUTPUT', @count=@count OUTPUT;

答案 1 :(得分:0)

为什么不简单?

IF (SELECT COUNT(*) FROM Product = 12) > 0 BEGIN...

我看不到为什么COUNT语句需要动态;为什么?没有任何动态。

此外,使用SQL '... WHERE p.ThruDate > GETDATE() '+@Where是一个糟糕的主意。如果@where是参数,它将打开以进行SQL注入。

答案 2 :(得分:0)

尝试这个。返回受上一个查询影响的行数: select @@Rowcount

答案 3 :(得分:0)

select name,date from (
select date1Name as name,date1 as date from table 
union all
select date2Name as name,date2 as date from table
union all
select date3Name as name,date3 as date from table ) as dd  order by date desc limit 1