0

In ADO.NET we have methods for starting a transaction, reading the query results, etc. My question is, will such T-sql statements as BEGIN TRANSACTION and particularly TRY-CATCH work if I just include them to command-text and then ExecuteNonQuery?

mySqlCommand.CommandText = 
@"BEGIN TRY
    SELECT TOP 1 [id] FROM myTable;
END TRY
BEGIN CATCH
    SELECT ERROR_NUMBER() AS ErrorNumber;
END CATCH;"

var result = mySqlCommand.ExecuteScalar(); // or just  mySqlCommand.ExecuteNonQuery()

PS: I know, I can just test this myself. But I am asking this as SO. So that afterwards someone like me will be able to just google that. So, obviously, I don't expect answers like 'why not just try'. Thank you.

Artur Udod
  • 4,465
  • 1
  • 29
  • 58

2 Answers2

2

Any valid T-SQL or a stored procedure are valid for SqlCommand.CommandText. So in short, yes you can if you are using SQL Server 2005 or greater. However it would be best to use this in a stored procedure.

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.commandtext.aspx

Darren
  • 68,902
  • 24
  • 138
  • 144
2

You can do this (with ExecuteScalar)

But it adds no value because you should have .net error handling anyway. Let's say you have a varchar from the SELECT but int from the CATCH block too: you now have 2 different datatypes to consume.

TRY/CATCH is more intended for stored procedures and to handle transaction, as per Nested stored procedures containing TRY CATCH ROLLBACK pattern?

Community
  • 1
  • 1
gbn
  • 422,506
  • 82
  • 585
  • 676