求 SQL in 里面的变量查询 写法

zjgkingdee 2010-08-18 12:39:19
1:查询的原型
select * from fype in( 11,12 )
ftyep 表示单据类型 int 类型.

但是现在 fype in ()里面的内容是不确定的

@declae
@ftype varchar(255)
set @ftype='11,12 '

select * from fype in(@ftype ) 的查询结果 跟 select * from fype in( 11,12 ) 是不一样的.


select * from fype in(@ftype ) 这样查询是一条记录么有
select * from fype in( 11,12 ) 是有记录的.
请问SQL in 里面的变量查询 不要用 动态的SQL语句
...全文
236 13 打赏 收藏 转发到动态 举报
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
SQLCenter 2010-08-18
  • 打赏
  • 举报
回复
昏,你写的什么语句, from fype in ?

select * from tb where fype in (??)

一定要动态
SQLCenter 2010-08-18
  • 打赏
  • 举报
回复
declare @list varchar(100)
set @list = '11,12'

exec ('select * from fype in('+@list+')')
zjgkingdee 2010-08-18
  • 打赏
  • 举报
回复
顶起来
zjgkingdee 2010-08-18
  • 打赏
  • 举报
回复
[Quote=引用 12 楼 josy 的回复:]

引用 11 楼 zjgkingdee 的回复:
已经测试可以了, josy 非常感谢你. 可否简单说下 原理 .


看看charindex(参数1,参数2)函数的用法,就是返回参数1在参数2中的起始位置
这个位置大于0,说明参数1在参数2中是存在的

前后加逗号, 是为了避免找1的时候却把11,12,111等也找出来
[/Quote]

明白了.感谢josy的帮助.
百年树人 2010-08-18
  • 打赏
  • 举报
回复
[Quote=引用 11 楼 zjgkingdee 的回复:]
已经测试可以了, josy 非常感谢你. 可否简单说下 原理 .
[/Quote]

看看charindex(参数1,参数2)函数的用法,就是返回参数1在参数2中的起始位置
这个位置大于0,说明参数1在参数2中是存在的

前后加逗号, 是为了避免找1的时候却把11,12,111等也找出来
zjgkingdee 2010-08-18
  • 打赏
  • 举报
回复
已经测试可以了, josy 非常感谢你. 可否简单说下 原理 .
mxbhot85 2010-08-18
  • 打赏
  • 举报
回复
6楼的思路不错,顶下
SQLCenter 2010-08-18
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 zjgkingdee 的回复:]
但是不想用 动态SQL 语句
[/Quote]

那就要多个变量

declare @1 bigint, @2 bigint, @3 bigint, @4 bigint

select top 1 @1 = id from sysobjects order by id
select top 1 @2 = id from sysobjects order by id desc

select * from sysobjects where id in (@1,@2,@3,@4)
zjgkingdee 2010-08-18
  • 打赏
  • 举报
回复
先感谢下josy 的答复.上次的疑难答复也是你帮我解决的.
mxbhot85 2010-08-18
  • 打赏
  • 举报
回复
如果不用动态语句的话,而且in里面参数的个数是确定的,可以这样做

declare @a int
declare @b int
set @a =11
set @b = 12
select * from table where fype in (@a,@b)


如果in中的参数有多个,那就比较绕了

百年树人 2010-08-18
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 zjgkingdee 的回复:]

但是不想用 动态SQL 语句
[/Quote]

declare @ftype varchar(255)
set @ftype='11,12'
select * from tb where charindex(','+ltrim(fype)+',',','+@ftype+',')>0
zjgkingdee 2010-08-18
  • 打赏
  • 举报
回复

不好意思 我写错了 忘写 from 表了
select * from tb where fype in (212,213)
想用变量替代 in 里面的内容
@ftype varchar(255)
set @ftype='11,12 '
select * from tb where fype in (@ftype)

但是不想用 动态SQL 语句
zjgkingdee 2010-08-18
  • 打赏
  • 举报
回复
是不能用 动态SQL 语句

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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