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?
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?
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
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
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