SQL TRY CATCH 在 Select 语句中的 CONVERT

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/920760/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 02:14:47  来源:igfitidea点击:

TRY CATCH on a CONVERT in a Select Statement

sqltsqldatetimetry-catch

提问by JohnIdol

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

是否可以在 SQL Selects 中使用 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?

处理这种情况的最佳方法是什么?

回答by Robin Day

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

回答by user10633

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

回答by gbn

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

回答by freggel

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

我认为在 select 中不可能有 try catch,但是当您使用存储过程时,在外部是可能的。

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

回答by A-K

You can use the function ISDATE():

您可以使用函数 ISDATE():

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