CREATE TABLE [dbo].[p_result] (
[num] [int] IDENTITY (1, 1) NOT NULL ,
[pro_date] [smalldatetime] NOT NULL ,
[ban] [char] (1) COLLATE Chinese_PRC_CI_AS NOT NULL ,
[s01] [int] NULL ,
[s02] [int] NULL ,
[s03] [int] NULL ,
[s04] [int] NULL ,
[s05] [int] NULL ,
[s06] [int] NULL ,
[s07] [int] NULL ,
[s08] [int] NULL ,
[s09] [int] NULL ,
[s10] [int] NULL ,
[s11] [int] NULL ,
[s12] [int] NULL ,
[s13] [int] NULL ,
[s14] [int] NULL 
) ON [PRIMARY]
GO
以上结构的表,但表中以s开头的列的列数不能确定(需要使用动态sql语句),该表的行数也不能确定,现在我想依次得到以s开头的列每一个值。
--------------------------------------------
我的已有部分程序如下,但是其中的动态sql语句能通过编译,但执行时会提示有语法错误。
希望大家帮忙看看
declare @SS varchar(10),@val int,@S nvarchar(1000),@pa nvarchar(20),@vv int,@i int,@k int,@h_s int,@l_s int
Select @l_s=Count(*) From sysobjects,syscolumns where sysobjects.id = syscolumns.id and
sysobjects.name = 'p_result'
select @h_s=count(*) from p_result
select @k=4
while @k<=@l_s
begin
   if @k<=13
      set @SS='s0'+convert(varchar(1),@k)
   else
      set @SS='s'+convert(varchar(2),@k)
   set @i=1
   while @i<=@h_s
      begin
        --(下面的动态语句能通过编译,但执行时会提示:'p_result' 附近有语法错误。希望大家帮忙看看)---
        select @pa='@val int out'
        set @S='select @val='+@SS+'from p_result where num='+convert(varchar(2),@i)
        execute   sp_executesql   @S,@pa,@vv out 
        -----------------------------------------------------------------------------------------
        select @vv --得到目标值
        set @i=@i+1
      end
set @k=@k+1
end 
谢了

解决方案 »

  1.   

    /*
    set @S='select @val='+@SS+'from p_result where num='+convert(varchar(2),@i)
    */
    set @S='select @val='+@SS+' from p_result where num='+convert(varchar(2),@i)
      

  2.   

    Limpire(昨夜小楼) 
    谢谢,你的回答
    再加上空格之后,可以执行了,但是有提示:'=*' 附近有语法错误。能否再帮我找找原因
      

  3.   

    整个语句楼上想要怎样的功能,贴出来的语句漏点不少...
       if @k<=13
          set @SS='s0'+convert(varchar(1),@k)
       else
          set @SS='s'+convert(varchar(2),@k)
    比一段是取列名的判断有问题,转换同样有问题
    改为
       if @k<10
          set @SS='s0'+rtrim(@k)
       else
          set @SS='s'+rtrim(@k)
      

  4.   

    convert(varchar(2),@k)--这样转换也就是楼主所说的=*
      

  5.   

    convert(varchar(2),@i)
    --
    同楼
    rtrim(@i)隐性转换
      

  6.   

    roy_88(中国风_燃烧你的激情!!!)终于可以运行了,谢谢你马上结贴给分