简体   繁体   English

SQL 错误在视图中将 nvarchar 转换为数字

[英]SQL error convert nvarchar to numeric in a view

I have the following table.我有下表。 The current column type of totalsales is (nvarchar(max), null) . totalsales 的当前列类型是(nvarchar(max), null) The requirement is to change this column type to a numeric value in a SQL view.要求是在 SQL 视图中将此列类型更改为数值。

I tried to do the following:我尝试执行以下操作:

CAST([totalsales] AS numeric) AS [totalsales]

This statement doesn't work after I run the query on the view.在视图上运行查询后,此语句不起作用。 Any suggestions?有什么建议? Many thanks!非常感谢!

在此处输入图片说明

Replace comma (,) with empty and then convert to numeric (assuming this column will always have only numeric values).逗号(,)替换为空,然后转换为数字(假设此列始终只有数字值)。

select id, totalsales as totalsales_nvarchar
 ,cast(replace(totalsales, ',','') as numeric) AS totalsales_numeric 
from tb1

在此处输入图片说明

Ok!好的! Lets try this:让我们试试这个:

alter table <table_name> modify <column_name datatype>;
  • for example: • Lets say we've created a table 'SAMPLE' with two columns 'ID' and 'NAME' having datatype as 'VARCHAR' each.(Here's the query)例如: • 假设我们创建了一个表 'SAMPLE',其中包含两列 'ID' 和 'NAME',每列的数据类型为 'VARCHAR'。(这是查询)

    create table sample(id varchar(10), name varchar(20));创建表样本(id varchar(10), name varchar(20));

• But then we fond a flaw in it that the 'ID' column should have datatype as 'NUMBER'. • 但是我们喜欢其中的一个缺陷,即“ID”列的数据类型应为“NUMBER”。

• Hence, we rectify our mistake by altering the table as==>> • 因此,我们通过将表更改为==>>来纠正我们的错误

alter table sample modify id number;

and when we describe table, now we have this;当我们描述表格时,现在我们有了这个; ID column perfectly carrying a datatype as 'NUMBER' ID 列完美携带数据类型为“NUMBER”

TABLE SAMPLE
Column  Null?   Type
ID       -      NUMBER
NAME     -      VARCHAR2(20)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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