如何将'1,2,3'转换为Int类型以便使用in语句

earthpea 2010-06-12 04:54:18
写了一个权限控制的小代码,读取时报错
消息 245,级别 16,状态 1,第 1 行
在将 varchar 值 '1,2,3,4,5,6,7,8,9,10' 转换成数据类型 int 时失败。
请大家帮忙看一下
create table t_a
(a_id int,
a_name varchar(10)
)

insert into t_a(a_id ,a_name)
select 1,'功能一'
union select 2,'功能二'

create table t_b
(b_id int,
b_name varchar(20),
b_content varchar(50))

insert into t_b(b_id,b_name,b_content)
select 1,'权限一','1,2'

create table t_c
(c_name varchar(10),
c_role int)

insert into t_c(c_name,c_role)
select '测试一',1



运行下面的语句成功:

select * from t_b where a_id in (1,2)

但运行下面的就出错:
select * from t_a
where a_id in (
select b.role_content from t_c c, t_b b
where c.c_role = b.b_id
)

sql语句应该成了:
select * from t_b where a_id in ('1,2')
这种方式,但怎么才能处理正常呢?
...全文
125 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
永生天地 2010-06-12
  • 打赏
  • 举报
回复
select a.* from t_a a,t_c c, t_b b
where charindex(','+ltrim(a.a_id)+',',','+ b.b_content+',' )>0
and c.c_role = b.b_id
/*
a_id a_name
----------- ----------
1 功能一
2 功能二

(所影响的行数为 2 行)
*/
winstonbonaparte 2010-06-12
  • 打赏
  • 举报
回复
select * from t_a
where a_id in (
select b.role_content from t_c c, t_b b
where c.c_role = b.b_id
)

这个语句返回的是一个列,两行的值。返回的是一个表,而并不是('1,2')
chuifengde 2010-06-12
  • 打赏
  • 举报
回复
select * from t_a aa where exists(
select 1 from t_c c, t_b b
where c.c_role = b.b_id and charindex(','+ltrim(a_id)+',',','+role_content+',')>0)

34,576

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧