获取存储过程的定义

时间:2019-05-24 21:30:24

标签: c# sql-server stored-procedures

我尝试了以下查询的各种方法,但由于我的一生,无法弄清无法从常规ADO.NET返回存储过程的定义

declare @procName varchar(100) = 'spGetMerchantSDR'
declare @Def varchar(max)

if OBJECT_ID('tempdb..#temp') is not null 
    drop table #temp

select @Def = m.[definition]
from sys.procedures p
inner join sys.sql_modules m on p.object_id = m.object_id
where p.name = @procName

select @Def as ProcText

程序摘要

using (var con = new SqlConnection(neededString))
{
    con.Open();

   using (var cmd = new SqlCommand(CmdText, con))
    {
        cmd.CommandType = CommandType.Text;

        using (var rdr = cmd.ExecuteReader())
        {
            if (rdr.Read())
            {
                item.Definition = rdr["ProcText"].ToString();
            }
        }
    }
}

当我在SSMS中运行查询时,我得到了预期的结果。如果更改查询以从sys.sql_modules返回所有内容,则可以获取诸如object_id之类的值,但是每次从C#中,定义都以空字符串形式返回。当我在SSMS中运行它时,我得到了预期的结果。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

SqlParameter param  = new SqlParameter();
param.ParameterName = "@procName";
param.Value = "spGetMerchantSDR";
cmd.Parameters.Add(param);
SELECT ISNULL(smsp.definition, ssmsp.definition) AS [ProcText]
FROM sys.all_objects AS sp
LEFT OUTER JOIN sys.sql_modules AS smsp ON smsp.object_id = sp.object_id
LEFT OUTER JOIN sys.system_sql_modules AS ssmsp ON ssmsp.object_id = sp.object_id
WHERE sp.type = N'P' and is_ms_shipped = 0 and OBJECT_NAME(sp.object_id) = @procName