0

I have a design concern which I need to implement without using cursor.

There is source table 'A' which will have all column in varchar data type. I want to iterate over them and convert each column to destination table data type and if conversion/parsing fails, I need to log that row in extra error table.

Any suggestions to go ahead will be helpful.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Tukaram Bhosale
  • 348
  • 3
  • 17

3 Answers3

1

In SQL Server, you would use try_convert():

insert into t2 ( . . . )
    select . . .
    from (select try_convert(?, col1) as col1,
                 try_convert(?, col1) as col2,                
          from staging_t
         ) t
    where col1 is not null and col2 is not null and . . .;

Then run a second query to get the rows where the value is NULL.

If NULL is a permitted value in the staging column, then this is a bit more complex:

insert into t2 ( . . . )
    select new_col1, new_col2, . . .
    from (select try_convert(?, col1) as new_col1, col1,
                 try_convert(?, col1) as new_col2, col2,              
          from staging_t
         ) t
    where (new_col1 is not null or col1 is null) and
          (new_col2 is not null or col2 is null) and
          . . .;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

In Sql Server 2012 and up: each of these will return null when the conversion fails instead of an error.

Example of all varcharcol that would fail conversion to int:

 select id, varcharcol
 from a
 where try_convert(int,varcharcol) is null
Community
  • 1
  • 1
SqlZim
  • 37,248
  • 6
  • 41
  • 59
0

Use Above Query Using User Define Table Type

Create Type Table - Procedure - User Define Table Type

@UserDefineTypeTable UserDefineTypeTable readonly

insert into table1 col1, col2, col3

(select

type.col1, type.col2, type,col3

from @UserDefineTypeTable as type)

Yog
  • 1
  • 1