读书人

数据类型转换的有关问题

发布时间: 2012-07-23 09:42:19 作者: rapoo

求教:数据类型转换的问题
求教各位前辈:有两张表TA、TB
TA
Id int a1 varchar(50)
1 10,20
2 10,20,21

TB
b1 int b2 varchar(20)
10 桌子
15 书包
20 椅子
21 书本

执行以下语句

declare @a1 as varchar(50)
set @a1=(select a1 from TA where id=1 )

select * from TB
where AppId in ( @a1 )


预期结果:

b1 b2
10 桌子
20 椅子


但执行以上语句,系统报错:
服务器: 消息 245,级别 16,状态 1,行 6
将 varchar 值 '10,20' 转换为数据类型为 int 的列时发生语法错误。


谢谢啦!



[解决办法]
declare @a1 as varchar(50)
set @a1=(select a1 from TA where id=1 )

select * from TB
where charindex(','+ltrim(AppId)+',',','+@a1+',' )>0


[解决办法]

SQL code
declare @a1 as varchar(50)set @a1=(select a1 from TA where id=1 )exec('select * from TBwhere AppId in ('+@a1+')')
[解决办法]
SQL code
;with tt as (select a.id , a1 = substring(a.a1 , b.number , charindex(',' , a.a1 + ',' , b.number) - b.number) from TA a join master..spt_values  b on b.type='p' and b.number between 1 and len(a.a1)where substring(',' + a.a1 , b.number , 1) = ',')select TB.* from tt ,TB where tt.id = TB.id and tt.id=1 

读书人网 >SQL Server

热点推荐