19

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?

JohnIdol
  • 48,899
  • 61
  • 158
  • 242

5 Answers5

22

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
  • 100,552
  • 23
  • 116
  • 167
  • 6
    What if the Date Format is different? – Asher Oct 08 '12 at 13:52
  • My date fields are char(23) and doing ISDATE(datefield) = 1 returns no fields. Their format is yyyy-mm-dd hh:mi:ss.mmm and I guess ISDATE doesn't recognize that. – Zoey Mar 14 '19 at 15:21
14

In MS SQL Server 2012 there is a new construct that does exactly what is asked for:


SELECT 
    CASE WHEN TRY_CONVERT(float, 'test') IS NULL 
    THEN 'Cast failed'
    ELSE 'Cast succeeded'
END AS Result;
    GO

See also http://msdn.microsoft.com/en-us/library/hh230993.aspx

user10633
  • 273
  • 2
  • 6
3

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
  • 422,506
  • 82
  • 585
  • 676
2

You can use the function ISDATE():

SELECT ISDATE('11/13/2009')
SELECT ISDATE('13/11/2009')
C B
  • 1,677
  • 6
  • 18
  • 20
A-K
  • 16,804
  • 8
  • 54
  • 74
1

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
  • 552
  • 2
  • 6
  • 13