How can I determine the parameters required by an arbitrary piece of T-SQL?

前端 未结 3 1632
长发绾君心
长发绾君心 2020-12-05 15:46

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

For example, this query requires one

3条回答
  •  南笙
    南笙 (楼主)
    2020-12-05 16:16

    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)

    Edit: 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();
        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 also introduces sp_describe_undeclared_parameters which is of relevance but fails with this example as it needs to be able to deduce datatypes.

提交回复
热议问题