这句话SQL为什么不行?

Aimis 2012-07-17 01:53:26
MySQL存储过程中为什么这样写无法将记录数赋值给变量?

declare nMax int;
select nMaxId = count(*) from 表; -- 无法


=======================================================
想类似的在MsSQL中就可以:

declare @nMax int
select @nMax = count(*) from 表
...全文
131 12 打赏 收藏 转发到动态 举报
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
oO寒枫Oo 2012-07-17
  • 打赏
  • 举报
回复
select XX into
用into 的好
:=这种在函数里面使用会报错。
Korbin Luo 2012-07-17
  • 打赏
  • 举报
回复
select count(*) from 表名
查出来的结果是一个结果集,所以不能赋值给变量。
以下几种方式可以给变量赋值:
-- 方式 1
DECLARE cnt INT DEFAULT 0;
select count(*) into cnt from test_tbl;
select cnt;

-- 方式 2
set @cnt = (select count(*) from test_tbl);
select @cnt;

-- 方式 3
select count(*) into @cnt1 from test_tbl;
select @cnt1;

-- 多个列的情况下似乎只能用 into 方式
select max(status), avg(status) into @max, @avg from test_tbl;
select @max, @avg;
ACMAIN_CHM 2012-07-17
  • 打赏
  • 举报
回复
select @nMax := count(*) from 表
伴老思源 2012-07-17
  • 打赏
  • 举报
回复
或者

set @nMaxId = ( select count(*) from tb );
伴老思源 2012-07-17
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 的回复:]

引用 4 楼 的回复:

select count(*) into nMaxID from tb


这个我直接在workbench中好像不行:
SQL code

set @nMax = 0;
select count(*) into @nMax from tb;
select @nMax; -- 还是0
[/Quote]

应改为:

set @nMaxId = 0;
select count(*) into @nMaxID from tb limit 1;



select ... into语句
select col_name[,...] into var_name[,...] table_expr
这个select语法把选定的列直接存储到变量。因此,只有单一的行可以被取回。
伴老思源 2012-07-17
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 的回复:]

不是用 := 的吗?
            declare   nMax   int;
select nMaxId := count(*) from 表;

[/Quote]
+1
libo_sina 2012-07-17
  • 打赏
  • 举报
回复
declare nMax int;
select @nMax := count(domain) as j from trade_domain_setting;
select @nMax;

+-------------------------------------------------------------------+
测试了:ok!
说明在这个地址:http://www.cnblogs.com/qixuejia/archive/2010/12/21/1913203.html
Aimis 2012-07-17
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 的回复:]

select count(*) into nMaxID from tb
[/Quote]

这个我直接在workbench中好像不行:

set @nMax = 0;
select count(*) into @nMax from tb;
select @nMax; -- 还是0
rucypli 2012-07-17
  • 打赏
  • 举报
回复
select count(*) into nMaxID from tb
nicenight 2012-07-17
  • 打赏
  • 举报
回复
什么情况,没格式了:
    declare nMax int;
select nMaxId := count(*) from 表;
nicenight 2012-07-17
  • 打赏
  • 举报
回复
不是用 := 的吗?
    declare nMax int;
select nMaxId := count(*) from 表;
Aimis 2012-07-17
  • 打赏
  • 举报
回复
杀花不留

56,677

社区成员

发帖
与我相关
我的任务
社区描述
MySQL相关内容讨论专区
社区管理员
  • MySQL
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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