SQL“如果存在..."动态查询 [英] SQL "if exists..." dynamic query
问题描述
假设我有一个存储在这样的变量中的查询(它实际上是动态填充的,并且更复杂,但这是出于演示目的):
Suppose I have a query stored in a variable like this (it's actually dynamically populated and more complex, but this is for demonstration purposes):
DECLARE @Query VARCHAR(1000) = 'SELECT * FROM dbo.MyTable'
是否可以检查查询是否返回任何结果?像这样的东西,但这是行不通的:
Is there a way to check if the query would return any results? Something like this, but this doesn't work:
IF EXISTS (@Query)
BEGIN
-- do something
END
我想到的唯一方法是将结果放入临时表中,然后从中进行查询,但这并不理想,因为动态查询中的列可以变化,而且我真的不需要除了检查是否会返回某些行外,temp表完全出于任何原因.有更好的方法吗?
The only way that I can think of to do this is to put the results in a temp table and then query from that, but that is not ideal because the columns in the dynamic query can vary and I really don't need the temp table at all for any reason other than checking whether some rows would be returned. Is there a better way?
推荐答案
尝试执行动态查询
并使用 @@ RowCount
查找行的存在.>
Try Executing the Dynamic query
and use @@RowCount
to find the existence of rows.
DECLARE @Query NVARCHAR(1000) = 'SELECT * FROM [dbo].[Mytable]',
@rowcnt INT
EXEC Sp_executesql @query
SELECT @rowcnt = @@ROWCOUNT
IF @rowcnt > 0
BEGIN
PRINT 'row present'
END
这篇关于SQL“如果存在..."动态查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!