views:

947

answers:

4

Is it possible to use TRY CATCH blocks in SQL Selects?

For stuff similar to this for example:

select 
   order, 
   CONVERT(DATETIME, orderDate)
from orders

What's the best way of handling this scenario?

+6  A: 

I don't know about try-catch, but in SQL Server you have the ISDATE function and can there for do something like

CASE WHEN ISDATE(orderDate) = 1 THEN CONVERT(DateTime, orderDate) ELSE GETDATE() END
Robin Day
+1  A: 

You can use ISDATE:

SELECT ISDATE('11/13/2009') SELECT ISDATE('13/11/2009')

AlexKuznetsov
+1  A: 

In the SELECT clause itself, no.

You can test for a date though using ISDATE()

select 
   order, 
   CASE WHEN ISDATE(orderDate) = 1 THEN CONVERT(DATETIME, orderDate) ELSE NULL END
from orders
gbn
+1  A: 

I don't think a try catch is possible inside a select, but outside is possible when you're working with stored procedures.

begin try
    select cast(strartnr as int) from table
end try
begin catch 
    select 10000 from table
end catch
freggel