Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/86.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SQL-运行视图时出错,但在视图内部运行查询时出错_Sql_Sql Server_Views - Fatal编程技术网

SQL-运行视图时出错,但在视图内部运行查询时出错

SQL-运行视图时出错,但在视图内部运行查询时出错,sql,sql-server,views,Sql,Sql Server,Views,有人能解释一下,一旦查询被放置在视图中,它的功能是如何不同的吗?更具体地说,我注意到,在运行视图时,经常会出现数据类型转换错误,但在视图内部运行独立查询时则不会。例如: select cast(id as int(11)) as 'UserID', name, dob from myTable 查询运行得非常好。但是,在我将此查询保存为视图后: create view myView as ( select cast(id as int(11)) as 'UserID', name

有人能解释一下,一旦查询被放置在视图中,它的功能是如何不同的吗?更具体地说,我注意到,在运行视图时,经常会出现数据类型转换错误,但在视图内部运行独立查询时则不会。例如:

select 
 cast(id as int(11)) as 'UserID',
 name,
 dob
from myTable
查询运行得非常好。但是,在我将此查询保存为视图后:

create view myView as (
select 
 cast(id as int(11)) as 'UserID',
 name,
 dob
from myTable
)

然后尝试从myView中选择*运行视图,通常会出现转换错误,如“算术溢出将数据类型varchar转换为数值”。有人能解释一下,当查询存储为视图时,会发生哪些更改,从而导致此错误吗?

这可能与返回数据的顺序有关。如果返回所有行,常规查询可能会遇到错误。显然,
id
中的值不正确。解决这一问题的新方法是:

select (case when isnumeric(id) and id not like '%.%' then cast(id as int(11)) end) as UserID,
       name,
       dob
from myTable;

当然,“正确”的方法是将数字数据存储为数字而不是字符串。

这取决于您的数据,可能您的数据有空格、点或其他无法转换为int的内容。SQL Server的哪个版本允许int(11)的数据类型?也许您使用MySQL。不幸的是,我处理的是继承的DBs,我无法更改其结构。我只是不明白当我运行查询时,它是如何工作得很好的,但是一旦我创建了视图,视图就会出现数据类型转换错误。