How to check trigger in SqlServer?  
Author Message
Alessandro Camargo





PostPosted: Visual C# Express Edition, How to check trigger in SqlServer? Top

Hi,

How can I check if one trigger is enable or disable for one specific Sqlserver table via c#

Can I use some like this

ConnectionSqlServer.CreateCommand();

CommandSqlServer.ExecuteNonQuery();

cheers,




Visual Studio Express Editions25  
 
 
Andreas Johansson





PostPosted: Visual C# Express Edition, How to check trigger in SqlServer? Top

You probably would use ExecuteScalar() method instead to get a value returned.

In SQL Server 2005 something like this should be possible

CommandSqlServer.CommandText = "select is_disabled from sys.triggers where name = 'thetriggername'";
bool bIsDisabled = (bool)CommandSqlServer.ExecuteScalar();

Other versions of sql server probably differ.



 
 
Alessandro Camargo





PostPosted: Visual C# Express Edition, How to check trigger in SqlServer? Top

Hi Andreas,

Ok, it works. Just one questions is it safe to perform this bool convertion

(bool)CommandSqlServer.ExecuteScalar();

Should be a stupid question, but a I'm new in c#, so I would like to know.

cheers,



 
 
ahmedilyas





PostPosted: Visual C# Express Edition, How to check trigger in SqlServer? Top

no you cant do a direct cast...you would do a Convert.ToBoolean(CommandSqlServer.ExecuteScalar()) however its best to know what type of object you will be returned (bool/int etc...)

object theResult = CommandSqlServer.ExecuteScalar();

bool theFinalResult = Convert.ToBoolean(theResult);

..

..

 

[edit] - just saw Andreas reply - yes that would be the way of doing it...the way Andreas has shown, or this way



 
 
Andreas Johansson





PostPosted: Visual C# Express Edition, How to check trigger in SqlServer? Top

You can ofcourse do a direct cast. Usually if you do a ExecuteScalar() you know what the query is and what datatype it should return.

The Convert class will try to make sense out of more values than a cast will do so it might be an option but it still can be an issue.

If you expect the result to not always return a bool you should place the cast (or use of Convert.ToBoolean) inside a try catch block and catch the InvalidCastException.

bool b;
object o = sqlcommand.ExecuteScalar();
try
{
b = (bool)o;
//b = Convert.ToBoolean(o);
}
catch (InvalidCastException ex)
{
// Handle incorrect data
}