日期:2014-05-16  浏览次数:20392 次

sql循环查询赋值问题 第二次循环不起作用了

declare @n int,@i int,@c varchar(100),@ca varchar(100)
set @n = 1
set @ca=''

select @i=count(*) from tbDemo 
while @n<@i
begin
       select top 1 @c = code from tbDemo where code not in (@ca) order by id
       if @ca = ''
       begin       
set @ca = @c    
   end
   else
set @ca = @ca + ',' + @c
       
       set @n=@n+1
       print @c
end

输出为
0001
0002
0001 错误了
0001
...
------解决方案--------------------
因为你not in 一个字符串,这个要用动态SQL,我改了一下你的查询,你看是不是要这个结果
CREATE TABLE  tbDemo (id int,code VARCHAR(4))
INSERT INTO tbDemo
SELECT 1 id ,'0001' code
UNION ALL 
SELECT 2,'0002'
UNION ALL 
SELECT 3,'0003'
UNION ALL 
SELECT 4,'0004'
UNION ALL 
SELECT 5,'0005'

SELECT DISTINCT stuff((select ','+code from tbDemo b 
       for xml path('')),1,1,'') 'code'
from tbDemo 
/*
code
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
0001,0002,0003,0004,0005

*/

------解决方案--------------------
你[i]print @ca  就能明白为什么出现你现在的结果了吧
/*
0001
0001,0002
0001,0002,0001
*/

0001,0002这个值在你的表中不存在,所以还是会输出第一行的数据
------解决方案--------------------
@ca值为: 0001,0002  这是一个值 而不是你所理解的0001和0002两个值
表中没有这个值0001,0002   所以会查出来


declare @c nvarchar(max)
set @c='0001,0002'
select  code from tbDemo where code not in (@c) order by id
print @c


select  code from tbDemo where code not in (0001,0002) order by id

执行这两个查询 可以判断出来
------解决方案--------------------
declare @i int = 1
declare @c nvarchar(max),@code nvarchar(100)
declare @sql nvarchar(1000)
set @c=''
while @i <=5
begin
if @c=''
       begin       
        select top 1  @code= code from tbDemo where code not in (@c) order by id
set @c=@code
       end
else
begin
 set @sql = N'
select top 1 @code = code from tbDemo where code not in ('+@c+') order by id'
exec sp_executesql @sql,N'@