关于变量赋值的问题~~急

常飞梦
博客专家认证
2007-03-20 07:33:27
我想在一个表里求一个字段的最大值,想用执行字符串的方法实现,可是我用以下的方法写怎么也求不出,得出是空值。请问谁给分析一下~~

declare @str1 varchar(500)
declare @V_servicetable varchar(500)
declare @v_currentid numeric

set @V_servicetable='tb'

set @str1='select ' + cast(@v_currentid as varchar) + ' = max(id) from ' + @V_servicetable
print @v_currentid
exec (@str1)
...全文
218 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
hui_hui_2007 2007-03-20
  • 打赏
  • 举报
回复
又一种写法:
create table #
(
myid int
)

insert into #
select 1000 union all
select 2 union all
select 3 union all
select 23 union all
select 14 union all
select 26 union all
select 71 union all
select 29 union all
select 51 union all
select 392

select * from #

go

declare @str nvarchar(4000)
declare @maxid int
set @str = N'select @maxid = max(myid) from #'
exec sp_executesql @str,N'@maxid int out',@maxid out
select @maxid
hui_hui_2007 2007-03-20
  • 打赏
  • 举报
回复
我写了个示例,你看一下吧,呵
create table #
(
myid int
)

insert into #
select 1000 union all
select 2 union all
select 3 union all
select 23 union all
select 14 union all
select 26 union all
select 71 union all
select 29 union all
select 51 union all
select 392

select * from #

go

declare @str varchar(100)
set @str='declare @maxid int select @maxid=max(myid) from # print @maxid'
exec (@str)
OracleRoob 2007-03-20
  • 打赏
  • 举报
回复
--如何将exec执行结果放入变量中?

declare @v_currentid int, @sqls nvarchar(4000) ,@tb varchar(100)
set @tb='hb168_message30'

set @sqls='select @a=max(id) from ' + @tb
exec sp_executesql @sqls,N'@a int output',@v_currentid output
select @v_currentid

hui_hui_2007 2007-03-20
  • 打赏
  • 举报
回复
还有我想在后面加一个变量条件应该怎么加?
比如:
set @str1='select ' + cast(@v_currentid as varchar) + ' = max(id) from ' + @V_servicetable+ ' where id = '+ @v_currentid + ';'

可这样好像也有毛病!!
-------------------------
cast(@v_currentid as varchar) + ' = max(id)
有问题吧,为何这样写
常飞梦 2007-03-20
  • 打赏
  • 举报
回复
还有我想在后面加一个变量条件应该怎么加?
比如:
set @str1='select ' + cast(@v_currentid as varchar) + ' = max(id) from ' + @V_servicetable+ ' where id = '+ @v_currentid + ';'

可这样好像也有毛病!!
常飞梦 2007-03-20
  • 打赏
  • 举报
回复
我就是想用SQL的字符串给变量赋值,楼上的变量只能在SQL里能用,在外面就不能用了,我想在下面的语句还要调用这个变量!!
冷箫轻笛 2007-03-20
  • 打赏
  • 举报
回复
declare @str1 varchar(500)
declare @V_servicetable varchar(500)
set @str1 = ''
set @V_servicetable='tb'

set @str1 = '
declare @v_currentid numeric
select @v_currentid = max(id) from '+ @V_servicetable + '
print @v_currentid '

exec (@str1)
九斤半 2007-03-20
  • 打赏
  • 举报
回复
参考:

declare @str nvarchar(4000)
declare @i int
set @str = 'select @i = count(*) from sysobjects'
exec sp_executesql @str,N'@i int out',@i out
select @i

34,590

社区成员

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

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