如何使用转换函数快速定位选择查询中的不良数据?

huangapple go评论53阅读模式
英文:

How to fast locate bad data in a select query using cast function?

问题

在我的 SQL Server 数据库中,有一个 varchar 列 begintime,其中在表 t1 中的值类似于 2023/07/10

我使用以下代码:

select cast(begintime as date) from t1

来将其转换为日期,但它返回错误消息,说有一些数据无法转换。
在检查表中的所有值后,我最终发现了原因。有些数据的长度是12而不是10,末尾有一个回车和空格字符。我想知道在 SQL Server Studio 中是否有一些工具可以快速定位坏数据?任何帮助?
谢谢。

英文:

In my SQL Server database, there is a varchar column begintime which has value like 2023/07/10 in table t1.

I use

select cast(begintime as date) from t1 

to convert it to date and it return error message said some data can't be converted.
After checking all values in the table finally I found the reason. Some data 's length is 12 instead of 10,with a return and blank character in the end.I wonder is there some tools in sql server studio which can fast locate the bad data? Any help?
Thanks

答案1

得分: 0

使用CASTCONVERT内置函数将2023/7/10转换为2023/07/10

select CAST('2023/7/10' as date);
select CONVERT(date, '2023/7/10');

以上行代码如果日期可以转换,则返回结果,否则返回错误响应。

你可以使用TRY_CASTTRY_CONVERT,如果日期可以转换,则返回结果,否则返回NULL

select TRY_CAST('2023/17/10' as date); -- 返回 NULL
select TRY_CAST('2023/7/10' as date); -- 返回 2023-07-10
select TRY_CONVERT(date, '2023/27/10'); -- 返回 NULL
select TRY_CONVERT(date, '2023/7/10'); -- 返回 2023-07-10
英文:

use CAST or CONVERT built in functions to make 2023/7/10 as 2023/07/10

select CAST('2023/7/10' as date);
select CONVERT(date ,'2023/7/10');

above line's gives out put if date is valid to convert else gives error response.

you may use TRY_CAST or TRY_CONVERT this will give you out put if date is valid to convert else return NULL

select TRY_CAST('2023/17/10' as date); -- returns NULL
select TRY_CAST('2023/7/10' as date); -- returns 2023-07-10
select TRY_CONVERT(date ,'2023/27/10'); -- returns NULL
select TRY_CONVERT(date ,'2023/7/10'); -- returns 2023-07-10

huangapple
  • 本文由 发表于 2023年7月10日 12:09:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76650634.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定