I want to get queries in a SQL Server stored procedure text using antrl4 lexer and parser. For example, I have procedure text as follows:
ALTER PROCEDURE [dbo].[BookUpdate]
@Name nvarchar(max),
@BookId int,
@PublishingHouse nvarchar(255),
@PublicationYear smallint,
@Authors nvarchar(255),
@Description nvarchar(max),
@BookShelf int,
@UserId int,
@Cover varbinary(max),
@Id int OUT
AS
BEGIN
DECLARE @haveDouble int = 0
DECLARE @haveUser int = 1
SELECT @haveDouble = Id
FROM dbo.Books
WHERE Name = @Name
AND Authors = @Authors
AND PublicationYear = @PublicationYear
AND Id != @BookId
IF @UserId > 0
BEGIN
SELECT @haveUser = UserId
FROM dbo.Users
WHERE UserId = @UserId
END
SET @Id = 0
IF @haveDouble = 0 AND @haveUser > 0
BEGIN
UPDATE dbo.Books
SET [Name] = @Name,
[PublishingHouse] = @PublishingHouse,
[PublicationYear] = @PublicationYear,
[Authors] = @Authors,
[Description] = @Description,
[BookShelf] = @BookShelf,
[Cover] = @Cover,
[UserId] = @UserId
WHERE
Id = @BookId
SET @Id = @BookId
END
END
I want to get positions of queries "DECLARE @haveDouble int = 0", "DECLARE @haveUser int = 1" and others. How can I do that?
[1] SQL Server comes with a dedicated API for parsing T-SQL source coude, API included within Microsoft.SqlServer.TransactSql.ScriptDom
namespace. This namespace include parsers for every SQL Server version starting with SQL Server 2000 (= TSql80Parser
).
[2] Download
[3] You have to find all TSqlStatement
s having DeclareVariableStatement
type (see DeclareVariableStatement Class ). This class has following properties (among other properties): StartLine
, StartColumn
, StartOffset
, FirstTokenIndex
.
[4] Example:
using Microsoft.SqlServer.TransactSql.ScriptDom;
....
TSql120Parser SqlParser = new TSql120Parser(false);
IList<ParseError> parseErrors;
TSqlFragment result = SqlParser.Parse(new StringReader(SqlTextBox.Text),
out parseErrors);
TSqlScript SqlScript = result as TSqlScript;
foreach (TSqlBatch sqlBatch in SqlScript.Batches)
{
foreach (TSqlStatement sqlStatement in sqlBatch.Statements)
{
ProcessViewStatementBody(sqlStatement);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.