T-SQL查看语句顺序

时间:2012-12-05 11:58:02

标签: tsql sql-view

我有以下问题: 我有一个SQL表,其中包含一列中的文本和数字。我创建了两个视图来处理文本和数字。

如果我整体选择视图,它们按预期工作,但如果我在select语句中添加where语句,则会出现以下错误:

Conversion failed when converting the varchar value 'Thomas' to data type int.

我可以以某种方式告诉服务器在外部选择的那个之前申请内部视图的where语句吗?

请使用以下SQL代码重现错误:

create schema tst
go
create table tst.tbl(strValue varchar(10))
insert tst.tbl(strValue)
    values ('Thomas'), ('1991'), ('Reto'), ('21'), ('Strub')
go
create view tst.tblStr as
    select strValue
    from tst.tbl
    where isnumeric(strValue)=0
go
create view tst.tblInt as
    select cast(strValue as int) intValue
    from tst.tbl
    where isnumeric(strValue)=1

go

select * from tst.tblStr order by strValue --ok
select * from tst.tblInt order by intValue --ok

go

select * from tst.tblInt where intValue<100 --not ok

go

select * from tst.tbl where isnumeric(strValue)=1 and cast(strValue as int) < 100 --ok

go

drop view tst.tblInt
drop view tst.tblStr
drop table tst.tbl
drop schema tst

2 个答案:

答案 0 :(得分:0)

对视图tst.tblInt使用“case when”。

 create view tst.tblInt as
    select 
            case when isnumeric(strValue)=1 
                then cast(strValue as int)
                else 0 
            end  intValue

    from tst.tbl
    where isnumeric(strValue)=1 

答案 1 :(得分:0)

我相信您已经发布的答案,只需修改一行就可以查看

CREATE SCHEMA TST
GO
CREATE TABLE TST.TBL(STRVALUE VARCHAR(10))
INSERT TST.TBL(STRVALUE)
VALUES ('THOMAS'), ('1991'), ('RETO'), ('21'),('24'),('212'), ('STRUB')
GO
CREATE VIEW TST.TBLSTR AS
SELECT STRVALUE
FROM TST.TBL
WHERE ISNUMERIC(STRVALUE)=0
GO
CREATE VIEW TST.TBLINT AS
SELECT CAST(STRVALUE AS INT) INTVALUE
FROM TST.TBL
WHERE ISNUMERIC(STRVALUE)=1

GO

SELECT * FROM TST.TBLSTR ORDER BY STRVALUE --OK
SELECT * FROM TST.TBLINT ORDER BY INTVALUE --OK

GO

**SELECT * FROM TST.TBLINT WHERE ISNUMERIC(INTVALUE)<100 --NOW OK ;)**

GO

SELECT * FROM TST.TBL WHERE ISNUMERIC(STRVALUE)=1 AND CAST(STRVALUE AS INT) < 100 --OK

GO

DROP VIEW TST.TBLINT
DROP VIEW TST.TBLSTR
DROP TABLE TST.TBL
DROP SCHEMA TST