小编Chr*_*rry的帖子

SELECT中的MSSQL强制转换([varcharColumn]为int)在WHERE子句筛选出错误值之前执行

假设以下架构和查询:

请查看我们希望在varchar列中包含值的明显设计问题.

create table dbo.Parent (
    Id bigint NOT NULL,
    TypeId int NOT NULL
)

create table dbo.Child (
    Id bigint NOT NULL,
    ParentId bigint NOT NULL,
    TypeId int NOT NULL,
    varcharColumn varchar(300) NULL
)

select cast(c.varcharColumn as int)
from dbo.Parent p (nolock)
    inner join dbo.Child c (nolock)
        on p.Id = c.ParentId
            and c.TypeId = 2
where p.TypeId = 13
Run Code Online (Sandbox Code Playgroud)

休息时间:

由于无法转换为int的值,我们得到一个转换中断.在这种情况下:"123-1".奇怪的是,正在转换的值会从最终结果集中过滤掉.

例如,这会返回零结果

select c.varcharColumn
from dbo.Parent p (nolock)
    inner join dbo.Child c (nolock)
        on p.Id = c.ParentId
            and c.TypeId …
Run Code Online (Sandbox Code Playgroud)

sql sql-server sql-server-2008

6
推荐指数
2
解决办法
9467
查看次数

标签 统计

sql ×1

sql-server ×1

sql-server-2008 ×1