SQL Server - 仅在TRY_CAST成功时插入,如果不执行任何操作

时间:2017-12-22 08:11:35

标签: sql sql-server

我正在尝试插入带有CAST()的选择:

INSERT INTO table1 
  (table1_Numeric_Value)
SELECT
  TRY_CAST(e.text_found AS float) 
FROM
  Event AS e

问题是如果TRY_CAST()失败,那么整个插入就会停止。有没有办法只在TRY_CAST()成功时插入它?

3 个答案:

答案 0 :(得分:2)

只需在WHERE子句中添加一个条件:

INSERT INTO table1 
  (table1_Numeric_Value)
SELECT
  TRY_CAST(e.text_found AS float) 
FROM
  Event AS e
WHERE
  TRY_CAST(e.text_found AS float) IS NOT NULL

(服务器足够智能,只能执行一次转换)

为了完整起见,如果您希望任何失败转换以阻止所有行插入,请按以下方式编写查询:

declare @t table (
    text_value varchar(30)
)
declare @u table (
    val float
)

insert into @t(text_value) values ('1.0'),('def'),('2.0')

insert into @u(val)
select Val from (
select
    TRY_CAST(text_value as float) as Val,
    COUNT(*) OVER() as Cnt1,
    COUNT(TRY_CAST(text_value as float)) OVER() as Cnt2
from @t
) t
where Cnt1 = Cnt2

答案 1 :(得分:1)

使用where条件过滤掉所有NULL值。

<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<title>Canonical jqGrid example</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/themes/redmond/jquery-ui.min.css"/>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/free-jqgrid/4.15.2/css/ui.jqgrid.min.css"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/free-jqgrid/4.15.2/jquery.jqgrid.min.js"></script>

    <div>
      <h1>Grid 1</h1>
      <table id="Grid1"/>
    </div>

    <div>
      <h1>Grid 2</h1>
      <table id="Grid2"/>
    </div>

    <div>
      <h1>Grid 3</h1>
      <table id="Grid3"/>
    </div>

或者您可以将NULL值转换为您使用ISNULL或COALESCE选择的任何值:

INSERT INTO table1 
  (table1_Numeric_Value)
SELECT
  TRY_CAST(e.text_found AS float) AS table1_Numeric_Value
FROM
  Event AS e
WHERE
  TRY_CAST(e.text_found AS float) IS NOT NULL

上述两个查询的结果可能会有所不同,请根据您的要求进行选择。

答案 2 :(得分:0)

您可以使用ISNUMERIC函数并过滤掉任何空值。我猜你在数据中有字符串字符。在插入之前检查此查询,这将确保不会选择具有string个字符的行

SELECT
  TRY_CAST(e.text_found AS float) 
FROM
  Event AS e where ISNUMERIC(e.text_found) = 1--- Selects rows with numeric 
                                                               values
  and e.text_found is not null