I have a query regarding identifying SQL query types through which I want to make out if any DDL statements are getting executed.
Is there is any C# API available to identify whether the SQL query type is DDL or DML?
I have a query regarding identifying SQL query types through which I want to make out if any DDL statements are getting executed.
Is there is any C# API available to identify whether the SQL query type is DDL or DML?
In C# that's impossible except the parsing way proposed by devio.
To allow only DML statements to be executed you should use internal database security mechanisms. For example, move all DDL to stored procedure and "grant exec" to admin. Or grant "db_ddladmin" role to admin only.
Does your question refer to code analysis or execution analysis?
In code, search for CREATE, ALTER, and DROP statements (depending on your data access layer).
For execution analysis, you can create DDL Triggers.
UPDATE after comment
After reading your comment I think the best solution is to use SQL Server's permission system to restrict the capabilities of the interactive user.
Create a database or application role, assign a user to that role, and select the GRANTs needed by the user/role. Run the interactive SQL statements in the context of this new user.
This way you can set permissions per table/view/sp/etc. and per command (SELECT/INSERT etc), without the need to parse the SQL statements.
Run this code and at the end of it, you will have a summary of all DDL matches. Works perfect every single time!!
string matchedSQL;
//Parse DDL statements
Regex DDL = new Regex(@"(?<=\b(create|alter|drop)\s+(procedure|proc|table|trigger|view|function)\b\s\[dbo\].)\[.*?\]", RegexOptions.IgnoreCase);
Match match = DDL.Match(script);
while (match.Success)
{
matchedSQL += match.Groups[1].Value + " " + match.Groups[2].Value + " " + match.Value;
match = match.NextMatch();
}