sqloperatorsssmsnvarchar

Can I use "/" operator on nvarchar column type in SQL Server Management Studio?


I am trying to divide 2 columns which are defined as nvarchar, but SSMS throws an error saying you can not use / operator on nvarchar.

select 
    location, date, total_cases, total_deaths, 
    (total_deaths / total_cases) * 100
from 
    CovidDeaths#xlsx$
order by 
    1, 2

I am unable to divide the total_cases and total_deaths.


Solution

  • Try the following instead since you cannot divide "string" values. Consider converting or casting to a decimal value. I'm assuming total_cases is nonzero in my answer.

    select 
        location, 
        date, 
        total_cases, 
        total_deaths, 
        CONVERT(DECIMAL(18, 2), (CONVERT(DECIMAL(18, 2), total_deaths) / CONVERT(DECIMAL(18, 2), total_cases))) as [DeathsOverTotal]
    from CovidDeaths#xlsx$
    order by 1,2