日期:2014-05-18  浏览次数:20399 次

帮改改SQL
--   创建测试表
create   table   tb(id   int,name   nvarchar(20),des   nvarchar(50))
--   加入测试数据
insert   into   tb   values(1, 'a ', 'aa ')
insert   into   tb   values(2, 'b ', 'bb ')
insert   into   tb   values(3, 'c ', 'cc ')
insert   into   tb   values(4, 'd ', 'dd ')
insert   into   tb   values(5, 'e ', 'ee ')
insert   into   tb   values(6, 'f ', 'ff ')
insert   into   tb   values(7, 'g ', 'gg ')
insert   into   tb   values(8, 'h ', 'hh ')
insert   into   tb   values(9, 'i ', 'ii ')

select   *   from   tb

--   版本1
declare   @i   int,@sql   nvarchar(max)
set   @i=1
set   @sql= 'select   name   from   tb   where   id   =(select   top   1   id   from   tb   where   id   not   in   (select   top   '+str(@i)+ '   id   from   tb)) '
exec(@sql)

--   版本2
declare   @i   int,@sql   nvarchar(max),@content   nvarchar(50)
set   @i=1
set   @sql= 'select   '+@content+ '=name   from   tb   where   id   =(select   top   1   id   from   tb   where   id   not   in   (select   top   '+str(@i)+ '   id   from   tb)) '
print   @sql
exec(@sql)
print   @content

功能实现:从测试表中返回指定行指定列的值,方便其他函数调用,用@i控制行,@content为返回列(name)的值

因为上述动态SQL     @content为变量   无法实现,大家帮改一下     如有更好方法赠之,万分感谢...

------解决方案--------------------
create table tb(id int,name nvarchar(20),des nvarchar(50))
-- 加入测试数据
insert into tb values(1, 'a ', 'aa ')
insert into tb values(2, 'b ', 'bb ')
insert into tb values(3, 'c ', 'cc ')
insert into tb values(4, 'd ', 'dd ')
insert into tb values(5, 'e ', 'ee ')
insert into tb values(6, 'f ', 'ff ')
insert into tb values(7, 'g ', 'gg ')
insert into tb values(8, 'h ', 'hh ')
insert into tb values(9, 'i ', 'ii ')

declare @i int,@sql nvarchar(4000),@content nvarchar(50)
set @i=1
set @sql= 'select @content=name from tb where id =(select top 1 id from tb where id not in (select top '+str(@i)+ ' id from tb)) '
exec sp_executesql @Sql,N '@content nvarchar(20) output ',@content output
print @content