如何判断存储在变量中的 SQL 是否会返回任何行
如果我有一个存储在这样的变量中的 SQL 脚本:
DECLARE @SQL VARCHAR(MAX) = 'SELECT * FROM Employees WHERE Age > 80'
如果我要运行它,我如何判断 @SQL 是否会返回任何行?
实际上:
IF EXISTS(@SQL) print 'yes, there are rows' -- Dummy code -- does not work!
我想尝试这个,而不必在 @SQL 中运行脚本,将其插入表中并计算行数。
If I have a SQL script stored in a variable like this:
DECLARE @SQL VARCHAR(MAX) = 'SELECT * FROM Employees WHERE Age > 80'
How can I tell if @SQL would return any rows if I were to run it?
In effect this:
IF EXISTS(@SQL) print 'yes, there are rows' -- Dummy code -- does not work!
I would like to try this without having to run the script in @SQL, insert that into a table and them count the rows.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当然,您需要运行该脚本。为了避免将结果插入表中并计算行数,您可以使用 sp_executesql 和输出参数。
Of course you need to run the script. To avoid having to insert the result into a table and count the rows you can use
sp_executesql
and an output parameter.虽然马丁的答案也是有效的,但我们不能在执行脚本后使用 @@RowCount 吗?请
注意,查询中有一个变量声明,它显然不能与Exists()一起使用
While Martin's answer is also valid but can't we just use the @@RowCount after Executing the script? like
Note that the query has a variable declaration in it, which obviously cannot be used with Exists()
您可以尝试开箱即用的解决方案。
例如。跟踪名为 emp_over_80 的单个变量。每当您添加超过该年龄的员工时,emp_over_80++。当您删除一个时,emp_over_80 -
在每天开始时,运行查询以确定 emp_over_80 的值(可能是员工的生日)。然后,一整天,您都可以引用 emp_over_80 而不是重新运行 SQL 查询。
其他选择是让员工表按年龄排序。如果最后一个员工超过 80,那么您的查询将至少返回一行。
现在,许多人可能会说这些是可怕的编码实践,我同意他们的观点。但是,我没有看到另一种方法可以在查询运行之前神奇地知道查询的结果(甚至是部分结果)。
You can try an out-of-the-box solution.
For example. Keep track of a single variable called emp_over_80. Whenever you add an employee over that age, emp_over_80++. When you remove one, emp_over_80--
At the beginning of each day, run a query to determine the value of emp_over_80 (it may be an employee's birthday). Then, throughout the day, you can refer to emp_over_80 instead of re-running the SQL query.
Other options would be to keep the employee table sorted by age. If the last employee is over 80, then your query will return at least one row.
Now, many might say these are horrible coding practices, and I'd agree with them. But, I don't see another way to magically know the result (even a partial result) of a query before it runs.