SQL Server Casting to multiple datatype in SELECT doesn't get expected result

7jmck4yq  于 2023-11-16  发布在  其他
关注(0)|答案(1)|浏览(127)

I have a table A with columns: ColumnName, Minimum, Maximum, and DataType.

CREATE TABLE A (
    ColumnName varchar(50),
    Maximum decimal(38, 5),
    Minimum decimal(38, 5),
    DataType varchar(10)
);

They store values as exactly as their column name labels. They store column names of another table, table B, minimum value of that column, maximum value of that column, and data type of that column.

I am trying to get results in their respective data type.

I tried the following query:

SELECT 
    ColumnName,
    'Minimum' = 
        CASE
            WHEN DataType = 'int' THEN CAST(Minimum AS INT)
            WHEN DataType ='decimal' THEN CAST(Minimum AS DECIMAL(38, 4))
        END,
    Maximum,
    DataType
FROM A;

What I get is every row is cast to DECIMAL(38, 4) .

chhkpiq4

chhkpiq41#

SELECT 
    ColumnName,
    'Minimum' = FORMAT(Minimum, 
        CASE
            WHEN DataType = 'int' THEN 'N0'
            WHEN DataType ='decimal' THEN 'N2'
        END)
    Maximum,
    DataType
FROM A;

The other way would be to apply a different format but on the application side, either using DisplayFormat or DisplayFormatString or something similar.

相关问题