SQL“如果存在..."动态查询

编程入门 行业动态 更新时间:2024-10-28 14:33:44
本文介绍了SQL“如果存在..."动态查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

假设我有一个存储在这样的变量中的查询(它实际上是动态填充的,并且更复杂,但这是出于演示目的):

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“如果存在..."动态查询

本文发布于:2023-07-22 12:39:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1187588.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:动态   SQL   quot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!