我可以判断 ado.net DbCommand 是否是查询(在执行之前)
我正在尝试编写一个 Powershell 脚本来针对数据库运行通用 SQL 命令。这个想法是 Run-SQL“select ...”将针对当前打开的数据库运行 SQL 文本。如果SQL语句是一个查询,它应该返回一个DataTable。如果它是非查询(DDL 或 DML),则不应返回任何内容 ($null)。
为了做到这一点,我需要知道针对该命令执行哪个方法(ExecuteReader 或 ExecuteNonQuery)。有没有办法确定这一点? (如果有帮助的话,我很乐意准备命令)。
作为替代方案,我可以添加一个由用户提供的 -query 参数,它区分这两种情况,但作为潜在用户,我会发现这很烦人(因为在我看来,我已经说过它是否是我使用的 SQL 查询,为什么再说一遍?)
我的主要用途是 Oracle 数据库,因此 Oracle 特定的答案对我来说没问题,尽管我更喜欢通用的答案。
I am trying to write a Powershell script to run a general SQL command against a database. The idea is that Run-SQL "select ..." will run the SQL text against the currently open database. If the SQL statement is a query, it should return a DataTable. If it is a non-query (DDL or DML) it should return nothing ($null).
In order to do this, I need to know which method (ExecuteReader or ExecuteNonQuery) to execute against the command. Is there a way to determine this? (I'm happy to prepare the command if that helps).
As an alternative, I can add a -query argument to be supplied by the user, which distinguishes the two cases, but as a potential user, I'd find this annoying (as, in my view, I have already said whether it's a query by the SQL I used, why say again?)
My key use is for Oracle databases, so an Oracle-specific answer is OK with me, although I'd prefer something generic.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为无论是否是查询,您都可以使用 ExecuteReader 。它可能有点矫枉过正,但在一些快速实验中进行 UPDATE ($reader 返回任何内容)和 COUNT ($reader[0] 输出标量结果) - 它似乎有效。
I think you could just use ExecuteReader whether it's a query or not. It may be overkill but in some quick experiments with doing an UPDATE ($reader returns nothing) and a COUNT ($reader[0] outputs scalar result) - it just seems to work.
作为 Keith 所说的替代方案,您可以尝试
修剪,以防 SQL 命令有前导空格,因为 $sql = ' select ' 不会匹配“^ select”
As an alternative to what Keith said you could try
The trim is there in case the SQL command has a leading space since $sql = ' select ' won't match "^select"