【问题标题】:How to verify datatype before entering into the table如何在进入表之前验证数据类型
【发布时间】:2012-12-12 15:58:55
【问题描述】:

我在一个表中有四列

Id Int
Name varchar(2)
Address varchar (4)
Active bit

和具有相同列但具有 varchar 数据类型的源表。

Id varchar(100)
Name varchar(100)
Address varchar (100)
Active varchar(100)

我必须将数据从源表传输到目标表,但在传输时我需要检查我拥有的行是否具有正确的目标数据类型。如果不是,我需要将该完整行传输到某个错误表。例如:

ID Name Address Active
1  A     A       1
C  B     B       0
3  AAA   C       1 
4  D     D       0
5  K     K       102

如果上面表示源表并且只有第 1 行和第 4 行有资格转移到目标表,则其他行将被移动到错误表(如果可能,可能带有有效的描述)

【问题讨论】:

  • 肯定建议您考虑使用 SSIS 来完成这项任务,而不是尝试在 T-SQL 中完成。

标签: sql-server-2008 sqldatatypes


【解决方案1】:

像这样的

insert into destination
select * from source 
where (isnumeric(ID)=1 
        and 
        (ID not like '%[^0-9]%')
        and 
        RIGHT('00000000000'+ID,10) <= '2147483647'
      ) 
      and
      len(name)<=2
      and
      len(Address)<=4
      and
      active in ('0','1')

所以要插入到 ERRORS 表中,请在 WHERE 中使用 NOT

insert into ERRORS
select * from source 
where 
   NOT
     (
      (isnumeric(ID)=1 
        and 
        (ID not like '%[^0-9]%')
        and 
        RIGHT('00000000000'+ID,10) <= '2147483647'
      ) 
      and
      len(name)<=2
      and
      len(Address)<=4
      and
      active in ('0','1')
    )

SQLFiddle demo

【讨论】:

  • ISNUMERIC('£') 等于 1,但不能转换为 int。我想你想要ID not like '%[^0-9]%'
  • @Damien_The_Unbeliever:您的建议已解决问题。
  • 现在我知道了如何实现这个.. +1 我正在实现你的逻辑:)
  • @Zerotoinfinite 如果这个答案对你有用,请mark it as accepted
猜你喜欢
  • 2015-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-03
  • 2015-10-25
  • 1970-01-01
  • 1970-01-01
  • 2017-04-29
相关资源
最近更新 更多