给函数传值判断,返回表

ice9ying 2011-05-31 04:13:10
有个表A,我要查询时有两种情况
一种:select * from A where code like '%'
第二种情况: select * from A where code not like '七%'

所以我想做个函数,给这个函数传值0或1,然后判断
如果传来的值是1,就返回第一种sql语句查出的表
如果是2,就返回第二种

要怎么写这个函数~???
...全文
58 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
ice9ying 2011-05-31
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 wwwwgou 的回复:]
SQL code
--参考:
DECLARE @var INT
SET @var = 1

select *
from A
WHERE 1 = 1
AND (@var = 0 OR code LIKE '%') --当然,这一行可以不要^^,like '%'相当于1=1
AND (@var = 1 OR code not like '七%')
[/Quote]

对啊,我怎么没想到呢,这么简单的事。。。。。啊~~太谢谢了~~
Shawn 2011-05-31
  • 打赏
  • 举报
回复
--参考:
DECLARE @var INT
SET @var = 1

select *
from A
WHERE 1 = 1
AND (@var = 0 OR code LIKE '%') --当然,这一行可以不要^^,like '%'相当于1=1
AND (@var = 1 OR code not like '七%')
ice9ying 2011-05-31
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 qianjin036a 的回复:]
你恐怕不是要做函数,而是要做存储过程吧.用函数返回查出来的表,恐怕是不行的.
另外, like '%' 等于不写where 条件.


SQL code
create procedure getA
(@flg int)
as
begin
if @flg=1
select * from A
else
select * from A where code not……
[/Quote]

存储过程的话,我也是会的,但现在情况不允许使用存储过程
我需要select查出的内容,所以考虑用视图或函数
ice9ying 2011-05-31
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 ssp2009 的回复:]
SQL code
create function f_name(@num int)
returns table @tb()--A表字段
begin
if @num=1
insert into @tb select * from A where code like '%'
else
insert into @tb select * from A where co……
[/Quote]


这个不行.....得到的表列是出来了,但没有值
还有,应该是 returns @tb table才对吧?
-晴天 2011-05-31
  • 打赏
  • 举报
回复
你恐怕不是要做函数,而是要做存储过程吧.用函数返回查出来的表,恐怕是不行的.
另外, like '%' 等于不写where 条件.

create procedure getA
(@flg int)
as
begin
if @flg=1
select * from A
else
select * from A where code not like '七%'
end
go
--执行
exec getA 0
快溜 2011-05-31
  • 打赏
  • 举报
回复
create function f_name(@num int)
returns table @tb()--A表字段
begin
if @num=1
insert into @tb select * from A where code like '%'
else
insert into @tb select * from A where code not like '七%'
return
end

select * from dbo.f_name

27,579

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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