Is it possible to use TRY CATCH blocks in SQL Selects?
是否可以在SQL选择中使用TRY CATCH块?
For stuff similar to this for example:
对于类似的东西,例如:
select
order,
CONVERT(DATETIME, orderDate)
from orders
What's the best way of handling this scenario?
处理这种情况的最佳方法是什么?
5 个解决方案
#1
20
I don't know about try-catch, but in SQL Server you have the ISDATE function and can there for do something like
我不知道try-catch,但是在SQL Server中你有ISDATE函数,可以用来做类似的事情
CASE WHEN ISDATE(orderDate) = 1 THEN CONVERT(DateTime, orderDate) ELSE GETDATE() END
#2
11
In MS SQL Server 2012 there is a new construct that does exactly what is asked for:
在MS SQL Server 2012中,有一个新的构造完全满足要求:
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
另请参见http://msdn.microsoft.com/en-us/library/hh230993.aspx
#3
2
In the SELECT clause itself, no.
在SELECT子句本身,没有。
You can test for a date though using ISDATE()
您可以使用ISDATE()测试日期
select
order,
CASE WHEN ISDATE(orderDate) = 1 THEN CONVERT(DATETIME, orderDate) ELSE NULL END
from orders
#4
1
I don't think a try catch is possible inside a select, but outside is possible when you're working with stored procedures.
我不认为在select中可以尝试catch,但是在使用存储过程时可以使用外部。
begin try
select cast(strartnr as int) from table
end try
begin catch
select 10000 from table
end catch
#5
1
You can use the function ISDATE():
您可以使用ISDATE()函数:
SELECT ISDATE('11/13/2009')
SELECT ISDATE('13/11/2009')
#1
20
I don't know about try-catch, but in SQL Server you have the ISDATE function and can there for do something like
我不知道try-catch,但是在SQL Server中你有ISDATE函数,可以用来做类似的事情
CASE WHEN ISDATE(orderDate) = 1 THEN CONVERT(DateTime, orderDate) ELSE GETDATE() END
#2
11
In MS SQL Server 2012 there is a new construct that does exactly what is asked for:
在MS SQL Server 2012中,有一个新的构造完全满足要求:
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
另请参见http://msdn.microsoft.com/en-us/library/hh230993.aspx
#3
2
In the SELECT clause itself, no.
在SELECT子句本身,没有。
You can test for a date though using ISDATE()
您可以使用ISDATE()测试日期
select
order,
CASE WHEN ISDATE(orderDate) = 1 THEN CONVERT(DATETIME, orderDate) ELSE NULL END
from orders
#4
1
I don't think a try catch is possible inside a select, but outside is possible when you're working with stored procedures.
我不认为在select中可以尝试catch,但是在使用存储过程时可以使用外部。
begin try
select cast(strartnr as int) from table
end try
begin catch
select 10000 from table
end catch
#5
1
You can use the function ISDATE():
您可以使用ISDATE()函数:
SELECT ISDATE('11/13/2009')
SELECT ISDATE('13/11/2009')