简体   繁体   中英

How to convert nvarchar into int type for SQL Server

I tried to count the total the column [Trans Det Amt ex Tax] like the following:

SELECT 
    Loyalty_Type_Code, 
    COUNT([Loyalty_Number]), 
    FORMAT(SUM([Trans_Det_Amt_ex_Tax]), '##,###,###,##0')
FROM 
    CRM_POWERBI_RETAIL
WHERE 
    Trans_Hdr_Sale_Date BETWEEN '2019-01-01' AND '2019-10-31'
GROUP BY 
    Loyalty_Type_Code
UNION
SELECT 
    'TOTAL', 
    COUNT(*) AS CCC, 
    COUNT(*) AS BBB
FROM 
    CRM_POWERBI_RETAIL

I get this error:

Msg 245, Level 16, State 1, Line 39
Conversion failed when converting the nvarchar value '67,527,726,031' to data type int.

So I tried to convert this to INT type by using the following:

SELECT 
    CONVERT(INT, Trans_Det_Amt_ex_Tax)
FROM 
    CRM_POWERBI_RETAIL

But the result still said

Conversion failed when converting the nvarchar value '67,527,726,031' to data type int

Please let me know how to fix this.

Thank you for all answers.

Don't convert the value to a string:

SELECT Loyalty_Type_Code , COUNT([Loyalty_Number]),  
       SUM([Trans_Det_Amt_ex_Tax]))
FROM CRM_POWERBI_RETAIL
WHERE Trans_Hdr_Sale_Date BETWEEN '2019-01-01' AND '2019-10-31'
GROUP BY Loyalty_Type_Code
UNION
SELECT 'TOTAL', COUNT(*) AS CCC, COUNT(*) AS BBB
FROM CRM_POWERBI_RETAIL;

All the types in a UNION ALL need to be the same. If it sees a string and an integer -- as in the third column -- it will try to convert the string to an integer. That is not possible with commas.

Alternatively, you can convert both columns to strings. A simpler method uses GROUPING SETS :

SELECT COALESCE(Loyalty_Type_Code, 'Total'), 
       COUNT([Loyalty_Number]),  
       FORMAT(SUM([Trans_Det_Amt_ex_Tax]), '##,###,###,##0')
FROM CRM_POWERBI_RETAIL
WHERE Trans_Hdr_Sale_Date BETWEEN '2019-01-01' AND '2019-10-31'
GROUP BY GROUPING SETS ( Loyalty_Type_Code, () );

select CONVERT(bigint, Trans_Det_Amt_ex_Tax)

int cant hold number that big

If you want to convert the value to a string, try removing the commas and using a data type cast that is large enough to store that data:

SELECT CAST(REPLACE('67,527,726,031',',','') AS BIGINT);

This will strip the commas and store the data as a BIGINT .

I'm not 100% sure, but you may need to CAST the SUM as a larger data type if you're going to be adding up a lot of values.

DB Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM