以下存储过程实现:select count(*) from table_1212 where fromip(独立IP) in (select fromip from table_1211 union select fromip from table_1210
union select fromip from table_1209 union select fromip from table_1208
union select fromip from table_1207 union select fromip from table_1206
......)
但执行后总出错:
服务器: 消息 536,级别 16,状态 3,过程 pro_col,行 30
向 substring 函数传递了无效的 length 参数。
应该是:
set @sql='select count(*) from table_0101 where fromip in 
('+substring(@sql,1,len(@sql)-10)+')'出错,出现这种错误是不是因为len(@sql)-10)出现了负值 ,里面加一个 判断 就可以了,
但是小弟不知道应该怎么进行判断,请高手指教!------------------------
alter procedure pro_col 
as
declare @cur_col varchar(30) declare @sql varchar(1000)
set @sql=''declare cur_col cursor for
select distinct name from sysobjects  
where xtype='u' and name like 'table_01##' order by name
--从系统表中找出name like 'table_%的所有表,并建立游标open cur_colfetch next from cur_col into @cur_col  
--将游标名为cur_col的值赋给局部变量@cur_col
while @@fetch_status = 0 --如果读取数据成功begin   --select @flag=''+@cur_col+''
set @sql=@sql+' select fromip from '+@cur_col+' '+' union all '
fetch next from cur_col into @cur_col   end--
set @sql='select count(*) from table_0101 where fromip in 
('+substring(@sql,1,len(@sql)-10)+')'print @sql
exec (@sql)close cur_col
deallocate cur_colgoexec pro_col

解决方案 »

  1.   

    --tryset @sql='select count(*) from table_0101 where fromip in 
    ('+substring(@sql, 1, case when len(@sql)-10 < 0 then 0 else len(@sql)-10 end)+')'
      

  2.   

    好像是我遗留的问题,不好意思帮忙分析一下
    1,这个len(@sql)-10很难出现负值阿,毕竟前边拼接了相当多的字符2,declare @sql varchar(1000)声明到declare @sql varchar(1000)吧,免得字符超出范围3,如果可能是
    set @sql='select count(*) from table_0101 where fromip in 
    ('+substring(@sql,1,len(@sql)-10)+')'
    中有语法错误不妨在存储过程中声明declare @str1 varchar(8000),@str2 varchar(8000)
    然后最后
    set @str1='select count(*) from table_0101 where fromip in ('
    set @str2=substring(@sql,1,len(@sql)-10)+')'
    set @sql=@str1+@str2
    print @sql
    exec (@sql)
      

  3.   

    加上值判断条件后应该就可以的,谢谢了,
    set @sql='select count(*) from table_0101 where fromip in 
    ('+substring(@sql, 1, case when len(@sql)-10 < 0 then 0 else len(@sql)-10 end)+')'是可以的!
      

  4.   

    对了,大老,
    这种情况下是把table_0101也包含在与table_0101的比较范围内了,
    而实际上我只是想将table_0101的数据与table_0102,table_0103的数据进行比较而已,
    我将
    select distinct name from sysobjects  
    where xtype='u' and name like 'table_01##' order by name
    后头加上 where xtype='u' and name like 'table_01--' and name <>'table_0101'
    但返回的结果并不正确!
    请高手指路,谢谢!