SQL .NET 前端中的存储过程验证(类似于 SSMS 中的解析选项)

SQL Stored Procedure Validation in .NET Front End (Similar to Parse Option in SSMS)

我的前端应用程序有一个文本区域,用户可以在其中输入存储过程。我想验证 SP,类似于 SSMS (Ctrl+F5) 中的选项“Parse”。

我们有图书馆吗?或功能?要做到这一点?

提前致谢。

您可以使用 Microsoft.SqlServer.SqlManagementObjects 或简称 (SMO)

您需要致电

var options = new Microsoft.SqlServer.Management.SqlParser.Parser.ParseOptions
{
  BatchSeparator = "GO",
  CompatibilityLevel = Microsoft.SqlServer.Management.SqlParser.Common.DatabaseCompatibilityLevel.Version140 // depedning on the compatibilty level of your database.
};
var output = Microsoft.SqlServer.Management.SqlParser.Parser.Parser.Parse(inputString, options);

if(output.Errors.Any())
{
   // handle errors
}

这与执行 Parse 命令时从 SSMS 执行的代码相同。

为什么你不应该在 SQL 服务器上这样做:

  • SQL 注射
  • 不要依赖 SQL 服务器
  • 不要用 SQL 服务器没有的东西烧掉宝贵的 SQL 服务器 CPU。 (SQL 服务器是基础架构中昂贵的一部分 运行 它在 C# 中要便宜得多。)
  • 使用自定义兼容级别,独立于 SQL 服务器配置。
  • 如果要为 Azure SQL 解析,也可以使用
  • options.TransactSqlVersion

在SQL服务器中,可以运行一个命令导致下一个命令不执行。

要完全执行 parse 按钮的操作,请使用

SET NOEXEC ON;

之后的任何命令都不会执行,只会是 evaluated/compiled。 下面要恢复正常使用

SET NOEXEC OFF;

因此,为了简化您的应用程序而不使用 SMO,请使用以下策略:

SET NOEXEC ONSET NOEXEC OFF

包围您的查询
-- string yourSqlStatement  = "SET NOEXEC ON; " + textarea.Text + " SET NOEXEC OFF;"
-- execute the yourSqlStatement using your programming language

SQL Server Reference

您可以想到的另一个选择是,将过程创建为临时存储过程,仅供当前会话使用。一旦关闭连接,会话就会丢失。

msdn reference on CREATE PROCEDURE

Local or global temporary procedures can be created by using one number sign (#) before procedure_name (#procedure_name) for local temporary procedures, and two number signs for global temporary procedures (##procedure_name). A local temporary procedure is visible only to the connection that created it and is dropped when that connection is closed. A global temporary procedure is available to all connections and is dropped at the end of the last session using the procedure. Temporary names cannot be specified for CLR procedures.

The complete name for a procedure or a global temporary procedure, including ##, cannot exceed 128 characters. The complete name for a local temporary procedure, including #, cannot exceed 116 characters.

Usage scenario of Temporary stored procedure

CREATE PROCEDURE #TempProcedureName
AS
BEGIN
...
END

你会知道所有的错误,类似于永久存储过程。但是,该过程实际上并未在数据库中创建。如果最终用户确实要创建过程,post检查成功,可以永久创建过程。