有没有办法在SQL Server存储过程中查询注释?

时间:2018-03-13 17:21:02

标签: sql-server tsql stored-procedures

我希望显示我的存储过程的文档步骤。开始这个的最好方法是从我的存储过程中提取所有注释。有没有办法查询并只返回我的存储过程中的注释?

1 个答案:

答案 0 :(得分:2)

对于以“ - ”开头的评论,您可以使用Ngrams8K,如下所示:

DECLARE @storedproc varchar(8000) =
'-- Some Comments
SET NOCOUNT ON;

-- Some Comments

SELECT FirstName -- we only need the first name
FROM dbo.Users WHERE Id = @Id;';

SELECT *
FROM 
(
  SELECT
    lineNumber = row_number() over (ORDER BY d.p),
    wholeLine  = SUBSTRING
               (
                 @storedproc, 
                 d.p+l.d, -- delimiter position + delimiter length
                  isnull(nullif(charindex(char(10), @storedproc, d.p+l.d),0) - (d.p+l.d), l.s+l.d)
               )
  FROM (values (len(@storedproc), 1)) as l(s,d) -- length of the string and delimiter as "inline variables"
  CROSS APPLY
  (
    SELECT -(l.d) UNION ALL -- 0 would be fine too; I'm using -(l.d) to keep the formula uniform
    SELECT ng.position
    FROM dbo.NGrams8K(@storedproc, l.d) as ng
    WHERE token = char(10)
  ) as d(p) -- delimiter.position
) split
CROSS APPLY (VALUES (SUBSTRING(wholeLine, charindex('--', wholeLine), 8000))) txt(comment)
WHERE txt.comment LIKE '%--%';

<强>返回:

lineNumber  wholeLine                                         comment
----------  ----------------------------------------------    -----------------------
1           -- Some Comments                                  -- Some Comments
4           -- Some Comments                                  -- Some Comments
6           SELECT FirstName  -- we only need the first name  -- we only need the first name

对于使用NGrams2B的超过8,000个字符的过程,并将我的代码中的每个8000实例更改为输入字符串的长度。