如何确定用任意一张T-SQL所需的参数?所需、参数、SQL

2023-09-02 10:30:29 作者:▇▇▇▇刮开试试

基本上,我正在寻找一个相当于 SqlCommandBuilder.DeriveParameters ,将工作的任意T-SQL。

Basically, I'm looking for an equivalent to SqlCommandBuilder.DeriveParameters that will work for arbitrary T-SQL.

例如,下面的查询需要一个参数:

For example, this query requires one parameter:

SELECT @Foo [Foo], '@Bar' [Bar], @Baz [Baz]

基本上,我需要提取:

I basically need to extract:

new[] { "Foo", "Baz" }

从以上。我可以建立一个SQL分析器,但我有一个开放的连接到SQL Server,所以我preFER使用现有的选项,如果可能的。

From above. I could build a SQL parser, but I have an open connection to SQL server, so I'd prefer to use an existing option if possible.

修改

目前的的的是一个办法做到这一点,因为SQL Server商业智能开发工作室是能够做到这一点很成功。

There has to be a way to do this, because SQL Server's Business Intelligence Development Studio is able to do this very successfully.

修改2:

SQL BIDS是为了描述的结果执行以下命令:

SQL BIDS is executing this command in order to describe the results:

exec sp_executesql N'SET FMTONLY OFF;SET FMTONLY ON;SELECT @Foo [Foo], ''@Bar'' [Bar], @Baz [Baz]',
    N'@Foo sql_variant,@Baz sql_variant',
    @Foo=NULL,@Baz=NULL

这解释了它是如何确定的列,但它的可以的只是字符串分析得到的参数......

Which explains how it can determine the columns, but it may be just string parsing to get the parameters...

推荐答案

您可以使用的 Microsoft.Data.Schema.ScriptDom 这一点。我不熟悉它自己,但我只是想解析你的发言,可以看到该变量是在 ScriptTokenStream 集合(不知道是否有更简单的方法访问让他们保持或没有)

You can use Microsoft.Data.Schema.ScriptDom for this. I'm not familiar with it myself but I just tried parsing your statement and could see that the variables were accessible in the ScriptTokenStream collection (not sure if there is an easier way of getting hold of them or not)

编辑:从注释中发布的OP自己的code

Posting the OP's own code from the comments!

    var sql = "SELECT @Foo [Foo], '@Bar' [Bar], @Baz [Baz]";
    var p = new TSql100Parser(true);
    var errors = new List<ParseError>();
    var tokens = p.GetTokenStream(new StringReader(sql), errors);
    if (errors.Count == 0)
    {
        var variables = (from t in tokens where t.TokenType == 
                       TSqlTokenType.Variable select t.Text).ToArray();
    }

SQL Server 2012中还引入了 sp_describe_undeclared_pa​​rameters 的是相关的,但无法与本实施例,因为它需要能够推断出数据类型。

SQL Server 2012 also introduces sp_describe_undeclared_parameters which is of relevance but fails with this example as it needs to be able to deduce datatypes.