How to select data(with one decimal type) from a table and insert into another table (with different decimal type)

272 Views Asked by At

I want to select data from TABLE A and insert data into TABLE B. Though I know how to achieve this. I have used:

INSERT INTO TableA(column1, column2, column3, ...)
SELECT column1, column2, column3, ...
FROM TableB
WHERE condition;

But the challenge is the data type. The target TABLE A has a column with data type definition as

column1(decimal(16,3),null)

Whereas the table TABLE B has a column with data type definition as

column1(decimal(15,4),null)

Please help me here!

1

There are 1 best solutions below

2
Gordon Linoff On BEST ANSWER

It should be fine. SQL Server will automatically convert the values. If you have a very large value in B that doesn't fit in A, then you could get an error.

To solve that, use try_convert():

INSERT INTO TableA(column1, column2, column3, ...)
    SELECT TRY_CONVERT(decimal(15,4), column1), column2, column3, ...
    FROM TableB
    WHERE condition;

This will avoid a type conversion error.